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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?