gpt4 book ai didi

go - 将表单值附加到 Go 中的 GET/POST 请求

转载 作者:IT王子 更新时间:2023-10-29 01:39:45 25 4
gpt4 key购买 nike

我想定义一个 http.Client,它会自动将表单值附加到所有 GET/POST 请求。

我天真地尝试实现 http.RoundTripper,因为从另一个库复制/粘贴使用这种技术来修改每个请求的 header 。

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 : panic :运行时错误:分配给 nil 映射中的条目

我尝试将此添加到 (t *Transport) RoundTrip,但没有成功:

err := req.ParseForm()
misc.PanicIf(err)

我不知道我在做什么,有什么提示吗?

编辑:尝试在 cloneRequest 方法中复制 req.Form 值是没有意义的,因为 r.Form 无论如何都是空映射.

最佳答案

FormPostFormParseForm() 仅在接收请求时使用。发送请求时,传输期望数据被正确编码。

包装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。检查 multipart/form-dataapplication/x-www-form-urlencodedContent-Type header 以避免与其他类型的交互查询也可能是个好主意。

关于go - 将表单值附加到 Go 中的 GET/POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27301051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com