我想定义一个http.Client
,它自动将表单值附加到所有GET/POST请求。将表格值附加到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)
我不知道我在做什么,有什么提示?
编辑:有是在试图cloneRequest
方法复制req.Form
值是没有意义的,因为r.Form
是空的地图呢。
是否要添加请求参数或修改表单主体? – JimB 2014-12-04 19:07:47
@JimB我想将请求参数添加到每个请求。 – 2014-12-04 19:14:51
但是当有'multipart/form-data'或'application/x-www-form-urlencoded'时你打算做什么?你还想要为url添加一个参数吗? – JimB 2014-12-04 19:24:14