如何发送Golang HTTP请求的嵌套头

如何发送Golang HTTP请求的嵌套头,http,go,https,http-headers,Http,Go,Https,Http Headers,我在Ruby中有一个像下面这样的旧脚本,我正试图在Golang中复制它 RestClient::Request.execute( url: "myurl", method: :put, headers: { params: { foo: 'bar' } }) 这就是我目前在戈兰的情况: req, _ := http.NewRequest("PUT", url, nil) req.Header.Add("params", "{\"

我在Ruby中有一个像下面这样的旧脚本,我正试图在Golang中复制它

RestClient::Request.execute(
    url: "myurl",
    method: :put,
    headers: {
      params: {
        foo: 'bar'
      }
 })
这就是我目前在戈兰的情况:

req, _ := http.NewRequest("PUT", url, nil)
req.Header.Add("params", "{\"foo\": \"bar\"}")
client := &http.Client{}
rsp, err = client.Do(req)
这不起作用,但我不知道该怎么办。我是否需要以不同的格式设置该字符串

请求的标题为:

map[Accept:[*/*] Accept-Encoding:[gzip, deflate] User-Agent:[rest-client/2.0.2 (my_pc x86_64) ruby/2.4.2p198] Content-Length:[0] Content-Type:[application/x-www-form-urlencoded]]
使用httputil.DumpRequest的请求转储为:

PUT /my_path?foo=bar HTTP/1.1
Host: localhost:8080
Accept: */*
Accept-Encoding: gzip, deflate
Content-Length: 0
Content-Type: application/x-www-form-urlencoded
User-Agent: rest-client/2.0.2 (my_pc) ruby/2.4.2p198

看起来我只需要将信息作为查询参数放在路径中。除非我还有别的事要查。内容长度为0,因此也没有正文

我刚刚运行了您的Ruby代码,发现它实际上并没有发送任何标题,而是将查询参数添加到您的请求中:

PUT /?foo=bar HTTP/1.1
Accept: */*; q=0.5, application/xml
Accept-Encoding: gzip, deflate
User-Agent: Ruby
Host: localhost:8080
因此,您可以使用此代码在Go中复制它:

req, _ := http.NewRequest("PUT", url, strings.NewReader(`{"foo": "bar"}`))
client := &http.Client{}
rsp, err = client.Do(req)

没有嵌套头这样的东西。RestClient发送的请求实际上是什么样子的?@JimB将其添加到末尾。谢谢,对我来说,看起来我只需要一些查询参数。是的,看起来Ruby无缘无故地称它为头,它只是附加了查询字符串值。