亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

沒有為具有空/無負載的 PATCH 請求設置 Content-Length 標頭 - GoLang

沒有為具有空/無負載的 PATCH 請求設置 Content-Length 標頭 - GoLang

Go
滄海一幻覺 2022-06-27 10:42:55
我觀察到 Content-Length 標頭沒有為具有空/nil 有效負載的 PATCH 請求設置。即使我們手動設置它,req.Header.Set("content-length", "0")它實際上并沒有在發出的請求中設置。這種奇怪的行為(Go bug?)僅發生在 PATCH 請求中,并且僅在有效負載為空或 nil(或設置為 http.NoBody)時發生package mainimport (    "fmt"    "io/ioutil"    "net/http"    "strings")func main() {    url := "http://localhost:9999"    method := "PATCH"    payload := strings.NewReader("")    client := &http.Client {    }    req, err := http.NewRequest(method, url, payload)    if err != nil {        fmt.Println(err)    }    req.Header.Set("Authorization", "Bearer my-token")    req.Header.Set("Content-Length", "0") //this is not honoured    res, err := client.Do(req)    defer res.Body.Close()    body, err := ioutil.ReadAll(res.Body)    fmt.Println(string(body))}即使在最新的 go 版本中,這也是可重現的1.15。只需在一個簡單的 http 服務器上運行上面的代碼,然后自己看看。是否有任何解決方案/解決方法可以發送 Content-Length 設置為 0 的 PATCH 請求?
查看完整描述

1 回答

?
慕姐8265434

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" }) 


查看完整回答
反對 回復 2022-06-27
  • 1 回答
  • 0 關注
  • 165 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號