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

如何为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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器