直觀地說,我認為當您創建 MaxByteReader 并傳入 http.ResponseWriter 時,它會為您寫出狀態代碼。但事實并非如此,作者實際上在做什么?例子: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) }}但是當這個測試運行時,我得到了這個:http: request body too large--- FAIL: TestMaxBytesMiddleware (0.00s) main_test.go:37: expected 413 got 200如果我想要我認為這個函數所做的所需功能,我需要將我的 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()) }}那么那個作家到底是為了什么?
1 回答

拉風的咖菲貓
TA貢獻1995條經驗 獲得超2個贊
如果 MaxBytesReader 在讀取整個正文之前停止,它會在 writer 上設置一些標志,以確保在發送響應后關閉 HTTP 連接。通常服務器愿意從同一個連接中讀取另一個請求(HTTP keepalive),但是如果前一個請求的未讀位仍在管道中,它就不能這樣做,所以它必須關閉連接,強制客戶端如果要發送更多請求,則建立新連接。
這是使用私有requestTooLarge
方法完成的http.ResponseWriter
。
- 1 回答
- 0 關注
- 493 瀏覽
添加回答
舉報
0/150
提交
取消