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

我正在使用 Golang 1.4.2(从源代码构建),当我尝试通过 http.Client.Do() 发出 HTTP PUT 请求时,请求中缺少 Content-Length 标头。我所有的其他标题都被发送了......我做错了什么吗?当我通过 CURL 发出相同的请求时,将发送内容长度标头。我的请求是向 etcd 服务器发出的,该服务器将我的所有键设置为空值。虽然这有点新颖,但几乎没有用。:)


http://play.golang.org/p/pIoB--bXUT


package main


import (

    "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.1

Host: localhost

Content-Type: application/x-www-form-urlencoded

X-Content-Length: 33


ttl=&value=WHOAH+here+is+my+stuff


阿晨1998
浏览 534回答 2
2回答

繁星coding

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

长风秋雁

如果您说Content-Length未设置标头(实际上它是自动设置的,只是在转储时未显示),它会按设计工作,因为httputil.DumpRequest()即使您明确设置以下标头,它们也被排除在外:HostContent-LengthTransfer-EncodingTrailer见线317的go/src/net/http/httputil/dump.go。如果您确实发送请求而不是转储它,您将看到Content-Length与User-Agent和一起发送的标头Accept-Encoding。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go