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) {
|
||||
|
||||
Reference in New Issue
Block a user