Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

frame/g: issue g.client Can we add a method for customizing request header types #3760

Closed
wisonlau opened this issue Sep 6, 2024 · 2 comments

Comments

@wisonlau
Copy link

wisonlau commented Sep 6, 2024

Description

#3758

我在这个问题里面提到,如果我想避免请求头首字母被改变,只能用go官方的方法.gf官方的包能不能出多一个方法兼容.

Additional

No response

@gqcn
Copy link
Member

gqcn commented Oct 5, 2024

@wisonlau 你好,

  • 首先,在HTTP协议中,规范化的Header Key是首字母大写的,并且使用英文词连接符号-连接多个单词。
  • 其次,在goframegclient包中,是通过标准库的HTTP Header Set方法来设置的Header,具体源码在这里
    req.Header.Set(k, v)
  • 最后,如果实在是想要自定义与众不同的Header,那么可以考虑使用gclient的前置中间件来实现,具体请参考文档 https://goframe.org/pages/viewpage.action?pageId=7301625
  • 此外,给你一个示例吧:
package main

import (
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/gclient"
	"net/http"
)

func main() {
	c := g.Client()
	c.Use(func(c *gclient.Client, r *http.Request) (resp *gclient.Response, err error) {
		// 注意这里不要使用r.Header.Set方法设置Header,会被标准化转换为规范的Header Key
		r.Header["userid"] = []string{"10000"}
		resp, err = c.Next(r)
		return resp, err
	})
}

@gqcn gqcn closed this as completed Oct 5, 2024
@Issues-translate-bot
Copy link

Bot detected the issue body's language is not English, translate it automatically. 👯👭🏻🧑‍🤝‍🧑👫🧑🏿‍🤝‍🧑🏻👩🏾‍🤝‍👨🏿👬🏿


@wisonlau Hello,

  • First of all, in the HTTP protocol, the standardized Header Key is capitalized, and the English word connection symbol - is used to connect multiple words.
  • Secondly, in the gclient package of goframe, the Header is set through the HTTP Header Set method of the standard library. The specific source code is here https://github.com/gogf/gf/blob/ 183395f/net/gclient/gclient_request.go#L329
  • Finally, if you really want to customize a unique Header, you can consider using the gclient front-end middleware to implement it. For details, please refer to the document https://goframe.org/pages/viewpage.action ?pageId=7301625
  • Also, let me give you an example:
package main

import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/gclient"
"net/http"
)

func main() {
c := g.Client()
c.Use(func(c *gclient.Client, r *http.Request) (resp *gclient.Response, err error) {
// Be careful not to use the r.Header.Set method to set the Header here. It will be standardized and converted into a standard Header Key.
r.Header["userid"] = []string{"10000"}
resp, err = c.Next(r)
return resp, err
})
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants