1 回答

TA贡献1813条经验 获得超2个赞
您可以通过将 TransferEncoding 设置为如下方式来告诉 HTTP 客户端包含Content-Length值为 0 的标头:identity
url := "http://localhost:9999"
method := "PATCH"
client := &http.Client{}
req, err := http.NewRequest(method, url, http.NoBody)
if err != nil {
panic(err)
}
req.TransferEncoding = []string{"identity"}
req.Header.Set("Authorization", "Bearer my-token")
// req.Header.Set("Content-Length", "0")
请注意对原始代码的以下更改:
重要的是:
req.TransferEncoding = []string{"identity"}
指定空主体的惯用方式:(
http.NoBody
对发送长度没有影响)注释掉
req.Header.Set("Content-Length", "0")
,客户自己填写也更改为出现错误时恐慌,您可能不想继续
的传输编码identity
没有写入请求,所以除了 header 之外,Content-Length = 0
请求看起来和以前一样。
不幸的是,这没有记录(请随时向 Go 团队提出问题),但可以在以下代码中看到:
繁琐的细节:
transferWriter.writeHeader检查以下内容以写入Content-Length
标头:
// Write Content-Length and/or Transfer-Encoding whose values are a
// function of the sanitized field triple (Body, ContentLength,
// TransferEncoding)
if t.shouldSendContentLength() {
if _, err := io.WriteString(w, "Content-Length: "); err != nil {
return err
}
if _, err := io.WriteString(w, strconv.FormatInt(t.ContentLength, 10)+"\r\n"); err != nil {
return err
}
反过来,shouldCheckContentLength在长度为零的情况下查看传输编码:
if t.ContentLength == 0 && isIdentity(t.TransferEncoding) {
if t.Method == "GET" || t.Method == "HEAD" {
return false
}
return true
}
isIdentity验证这TransferEncoding正是:_ []string{"identity"}
func isIdentity(te []string) bool { return len(te) == 1 && te[0] == "identity" })
- 1 回答
- 0 关注
- 151 浏览
添加回答
举报