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 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程