fix: 限制管理接口请求体大小与读取时间
This commit is contained in:
+18
-2
@@ -8,6 +8,17 @@ import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
const maxJSONBodyBytes = 1 << 20
|
||||
|
||||
// IsBodyTooLarge 判断是否因请求体超过 MaxBytesReader 上限而失败。
|
||||
func IsBodyTooLarge(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
var maxErr *http.MaxBytesError
|
||||
return errors.As(err, &maxErr)
|
||||
}
|
||||
|
||||
// ErrorBody 是失败响应里的 error 对象。
|
||||
type ErrorBody struct {
|
||||
Code string `json:"code"`
|
||||
@@ -46,10 +57,15 @@ func WriteError(w http.ResponseWriter, status int, code, message string) {
|
||||
})
|
||||
}
|
||||
|
||||
// DecodeJSON 解码请求 JSON 体;空体对 dst 保持零值。
|
||||
// DecodeJSON 解码请求 JSON 体;空体对 dst 保持零值。内部把请求体限制在 1 MiB。
|
||||
func DecodeJSON(r *http.Request, dst any) error {
|
||||
defer func() { _ = r.Body.Close() }()
|
||||
dec := json.NewDecoder(r.Body)
|
||||
body := r.Body
|
||||
if body == nil {
|
||||
return nil
|
||||
}
|
||||
body = http.MaxBytesReader(nil, body, maxJSONBodyBytes)
|
||||
dec := json.NewDecoder(body)
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(dst); err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user