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

时间:2015-08-06 08:58:27

标签: http go put 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

2 个答案:

答案 0 :(得分:5)

关于Content-Length没有被发送我不正确,我在使用httputil.DumpRequest时没有看到它。

此处的解决方案是使用httputil.DumpRequestOut,它正确显示Content-Length标头(以及其他标头)。这意味着我的程序还有其他事情导致etcd设置空值。如果我知道这一点,我也会使用该解决方案进行更新。

答案 1 :(得分:3)

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

  • Host
  • Content-Length
  • Transfer-Encoding
  • Trailer

请参阅go/src/net/http/httputil/dump.go的{​​{3}}。

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