直觀(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
。
- 1 回答
- 0 關(guān)注
- 492 瀏覽
添加回答
舉報(bào)
0/150
提交
取消