第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

Go 的 http.MaxBytesReader,為什么要傳入 writer?

Go 的 http.MaxBytesReader,為什么要傳入 writer?

Go
Cats萌萌 2022-06-21 17:01:55
直觀(guān)地說(shuō),我認(rèn)為當(dāng)您創(chuàng)建 MaxByteReader 并傳入 http.ResponseWriter 時(shí),它會(huì)為您寫(xiě)出狀態(tài)代碼。但事實(shí)并非如此,作者實(shí)際上在做什么?例子:func maxBytesMiddleware(next http.Handler) http.Handler {    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {        r.Body = http.MaxBytesReader(w, r.Body, 1)        next.ServeHTTP(w, r)    })}func mainHandler(w http.ResponseWriter, r *http.Request) {    var i interface{}    err := json.NewDecoder(r.Body).Decode(&i)    if err != nil {        fmt.Println(err.Error())    }}func TestMaxBytesMiddleware(t *testing.T) {    handlerToTest := maxBytesMiddleware(http.HandlerFunc(mainHandler))    req := httptest.NewRequest(http.MethodPost, "http://test.com", bytes.NewReader(json.RawMessage(`{"hello":"world"}`)))    recorder := httptest.NewRecorder()    handlerToTest.ServeHTTP(recorder, req)    if recorder.Result().StatusCode != http.StatusRequestEntityTooLarge {        t.Errorf("expected %d got %d", http.StatusRequestEntityTooLarge, recorder.Result().StatusCode)    }}但是當(dāng)這個(gè)測(cè)試運(yùn)行時(shí),我得到了這個(gè):http: request body too large--- FAIL: TestMaxBytesMiddleware (0.00s)    main_test.go:37: expected 413 got 200如果我想要我認(rèn)為這個(gè)函數(shù)所做的所需功能,我需要將我的 mainHandler 更改為如下所示:func mainHandler(w http.ResponseWriter, r *http.Request) {    var i interface{}    err := json.NewDecoder(r.Body).Decode(&i)    if err != nil {        if err.Error() == "http: request body too large" {            w.WriteHeader(http.StatusRequestEntityTooLarge)            return        }        fmt.Println(err.Error())    }}那么那個(gè)作家到底是為了什么?
查看完整描述

1 回答

?
拉風(fēng)的咖菲貓

TA貢獻(xiàn)1995條經(jīng)驗(yàn) 獲得超2個(gè)贊

如果 MaxBytesReader 在讀取整個(gè)正文之前停止,它會(huì)在 writer 上設(shè)置一些標(biāo)志,以確保在發(fā)送響應(yīng)后關(guān)閉 HTTP 連接。通常服務(wù)器愿意從同一個(gè)連接中讀取另一個(gè)請(qǐng)求(HTTP keepalive),但是如果前一個(gè)請(qǐng)求的未讀位仍在管道中,它就不能這樣做,所以它必須關(guān)閉連接,強(qiáng)制客戶(hù)端如果要發(fā)送更多請(qǐng)求,則建立新連接。

這是使用私有requestTooLarge方法完成的http.ResponseWriter。


查看完整回答
反對(duì) 回復(fù) 2022-06-21
  • 1 回答
  • 0 關(guān)注
  • 492 瀏覽
慕課專(zhuān)欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢(xún)優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)