我想定义一个http.Client
自动将表单值附加到所有 GET/POST 请求。
我天真地尝试实施http.RoundTripper
从另一个库复制/粘贴时使用此技术来修改每个请求的标头。
type Transport struct {
// Transport is the HTTP transport to use when making requests.
// It will default to http.DefaultTransport if nil.
// (It should never be an oauth.Transport.)
Transport http.RoundTripper
}
// Client returns an *http.Client that makes OAuth-authenticated requests.
func (t *Transport) Client() *http.Client {
return &http.Client{Transport: t}
}
func (t *Transport) transport() http.RoundTripper {
if t.Transport != nil {
return t.Transport
}
return http.DefaultTransport
}
func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
// To set the Authorization header, we must make a copy of the Request
// so that we don't modify the Request we were given.
// This is required by the specification of http.RoundTripper.
req = cloneRequest(req)
>> req.Form.Set("foo", bar)
// Make the HTTP request.
return t.transport().RoundTrip(req)
}
// cloneRequest returns a clone of the provided *http.Request.
// The clone is a shallow copy of the struct and its Header map.
func cloneRequest(r *http.Request) *http.Request {
// shallow copy of the struct
r2 := new(http.Request)
*r2 = *r
// deep copy of the Header
r2.Header = make(http.Header)
for k, s := range r.Header {
r2.Header[k] = s
}
return r2
}
然而这不起作用。这req.Form
值映射在现阶段似乎不存在,所以我感到恐慌:panic: runtime error: assignment to entry in nil map
我尝试将其添加到(t *Transport) RoundTrip
,但没有运气:
err := req.ParseForm()
misc.PanicIf(err)
我不知道我在做什么,有什么建议吗?
编辑:尝试复制是没有意义的req.Form
值在cloneRequest
方法,因为r.Form
反正是空地图。
Form
, PostForm
, and ParseForm()
仅在收到请求时使用。发送请求时,传输层期望数据被正确编码。
通过包装你就有了正确的想法RoundTrip
,但是你必须自己处理编码数据。
if req.URL.RawQuery == "" {
req.URL.RawQuery = "foo=bar"
} else {
req.URL.RawQuery = req.URL.RawQuery + "&" + "foo=bar"
}
或者:
form, _ = url.ParseQuery(req.URL.RawQuery)
form.Add("boo", "far")
req.URL.RawQuery = form.Encode()
您还可以选择检查url.Values
如果您想避免重复密钥,请事先这样做。检查Content-Type
标题为multipart/form-data
or application/x-www-form-urlencoded
避免与其他类型的查询交互可能也是一个好主意。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)