fix: 限制管理接口请求体大小与读取时间

This commit is contained in:
Nixevol
2026-09-30 16:22:48 +08:00
parent b40ef5c548
commit 1a4bf6f185
7 changed files with 170 additions and 8 deletions
+39
View File
@@ -0,0 +1,39 @@
package httpx
import (
"bytes"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestDecodeJSONRejectsOversizeBody(t *testing.T) {
t.Parallel()
payload := `{"password":"` + strings.Repeat("a", 2<<20) + `"}`
req := httptest.NewRequest(http.MethodPost, "/x", strings.NewReader(payload))
var dst struct {
Password string `json:"password"`
}
err := DecodeJSON(req, &dst)
if err == nil {
t.Fatal("want error for 2 MiB JSON body")
}
if !IsBodyTooLarge(err) {
t.Fatalf("want IsBodyTooLarge, got %v", err)
}
}
func TestDecodeJSONAcceptsSmallBody(t *testing.T) {
t.Parallel()
req := httptest.NewRequest(http.MethodPost, "/x", bytes.NewReader([]byte(`{"password":"ok"}`)))
var dst struct {
Password string `json:"password"`
}
if err := DecodeJSON(req, &dst); err != nil {
t.Fatal(err)
}
if dst.Password != "ok" {
t.Fatalf("password=%q", dst.Password)
}
}