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 關注
- 165 瀏覽
添加回答
舉報