为了账号安全,请及时绑定邮箱和手机立即绑定

使用 PUT 方法在 Golang http 客户端请求中未设置 Content-Length 标头

使用 PUT 方法在 Golang http 客户端请求中未设置 Content-Length 标头

Go
阿晨1998 2021-10-25 20:30:37
我正在使用 Golang 1.4.2(从源代码构建),当我尝试通过 http.Client.Do() 发出 HTTP PUT 请求时,请求中缺少 Content-Length 标头。我所有的其他标题都被发送了......我做错了什么吗?当我通过 CURL 发出相同的请求时,将发送内容长度标头。我的请求是向 etcd 服务器发出的,该服务器将我的所有键设置为空值。虽然这有点新颖,但几乎没有用。:)http://play.golang.org/p/pIoB--bXUTpackage mainimport (    "bytes"    "fmt"    "net/http"    "net/http/httputil"    "net/url"    "strconv")func main() {    put := url.Values{}    put.Set("value", "WHOAH here is my stuff")    put.Add("ttl","")    encode := put.Encode()    req, _ := http.NewRequest("PUT", "http://localhost:2379/v2/keys/somekey", bytes.NewBufferString(encode))    req.Header.Add("Content-Type", "application/x-www-form-urlencoded")    req.Header.Add("Content-Length", strconv.Itoa(len(encode)))    req.Header.Add("X-Content-Length", strconv.Itoa(len(encode)))    dump, _ := httputil.DumpRequest(req, true)    fmt.Println(string(dump))}产量PUT /v2/keys/somekey HTTP/1.1Host: localhostContent-Type: application/x-www-form-urlencodedX-Content-Length: 33ttl=&value=WHOAH+here+is+my+stuff
查看完整描述

2 回答

?
繁星coding

TA贡献1797条经验 获得超4个赞

我对没有发送 Content-Length 的说法不正确,我只是在使用 httputil.DumpRequest 时没有看到它。

这里的解决方案是使用 httputil.DumpRequestOut 正确显示 Content-Length 标头(和其他)。这意味着我的程序还有其他事情导致 etcd 设置空值。如果我弄清楚了,我也会使用该解决方案进行更新。


查看完整回答
反对 回复 2021-10-25
?
长风秋雁

TA贡献1757条经验 获得超7个赞

如果您说Content-Length未设置标头(实际上它是自动设置的,只是在转储时未显示),它会按设计工作,因为httputil.DumpRequest()即使您明确设置以下标头,它们也被排除在外:

  • Host

  • Content-Length

  • Transfer-Encoding

  • Trailer

线317go/src/net/http/httputil/dump.go

如果您确实发送请求而不是转储它,您将看到Content-LengthUser-Agent和一起发送的标头Accept-Encoding


查看完整回答
反对 回复 2021-10-25
  • 2 回答
  • 0 关注
  • 533 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信