dtvfshi5248
2018-06-26 19:49
浏览 97
已采纳

如何为Golang HTTP请求发送嵌套标头

I have an older script like the following in Ruby that I'n trying to copy in Golang

RestClient::Request.execute(
    url: "myurl",
    method: :put,
    headers: {
      params: {
        foo: 'bar'
      }
 })

This is what I have so far in Golang:

req, _ := http.NewRequest("PUT", url, nil)
req.Header.Add("params", "{\"foo\": \"bar\"}")
client := &http.Client{}
rsp, err = client.Do(req)

This isn't working but, I'm not sure what to do. Do I need to format that string differently?

The header for the request is:

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]]

The request dump (using httputil.DumpRequest) is:

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

It looks like I just need to put the info in the path as query parameter. Unless there is something else I should check. The content length is 0 so there is not body either.

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dsl36367 2018-06-28 15:44
    已采纳

    I just ran your Ruby code and found out that it doesn't actually send any headers, instead it adds query params to your request:

    PUT /?foo=bar HTTP/1.1
    Accept: */*; q=0.5, application/xml
    Accept-Encoding: gzip, deflate
    User-Agent: Ruby
    Host: localhost:8080
    

    So you can just use this code to reproduce it in Go:

    req, _ := http.NewRequest("PUT", url, strings.NewReader(`{"foo": "bar"}`))
    client := &http.Client{}
    rsp, err = client.Do(req)
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题