【问题标题】:Content-Length header is not set in Golang http client request using PUT method [closed]使用 PUT 方法在 Golang http 客户端请求中未设置 Content-Length 标头[关闭]
【发布时间】:2015-08-06 08:58:26
【问题描述】:

我正在使用 Golang 1.4.2(从源代码构建),当我尝试通过 http.Client.Do() 发出 HTTP PUT 请求时,请求中缺少 Content-Length 标头。我所有的其他标头都已发送...我做错了吗?当我通过 CURL 发出相同的请求时,会发送 content-length 标头。我的请求正在向 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

【问题讨论】:

  • ehrm...您转储的请求似乎设置了Content-Type 标头。
  • 代码正在运行。不是问题。
  • 鉴于问题的其余部分,我怀疑他的意思是 Content-Length 标头:这是输出中未包含的标头。
  • 如果缺少内容长度,那么您需要 DumpRequestOut,因为该标头不是您可以覆盖的标头,并且由 Transport 设置。
  • @JimB DumpRequestOut 是我所需要的。谢谢!

标签: http go put content-length


【解决方案1】:

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

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

【讨论】:

  • 整体问题与 HTTP 请求无关,而是我用于 etcd 响应的 json 标签。我将 json 存储在 etcd 键/值中,并将其传递给 json.RawMessage 类型,我认为这对于后续对该数据的 json.Unmarshal 调用会更好。然而,问题是 json.RawMessage []bytes 被引用了,所以我需要在解组之前取消引用。我决定只使用字符串类型,并在传递给 json.Unmarshal 时转换为 []byte。
【解决方案2】:

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

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

参见line 317 中的go/src/net/http/httputil/dump.go

如果您发送请求而不是转储它,您将看到标头 Content-LengthUser-AgentAccept-Encoding 一起发送。

【讨论】:

  • NewRequest sets the content length 申请。
  • 是的,所以不需要在上面的代码中设置 content-length 头。它只是在之后从httputil.DumpRequest() 的转储结果中删除这些标头,尽管此标头仍然存在
猜你喜欢
  • 1970-01-01
  • 2011-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-21
  • 1970-01-01
  • 1970-01-01
  • 2018-04-06
相关资源
最近更新 更多