package request import ( "bytes" "errors" "io" "net/http" fault "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure" "github.com/gin-gonic/gin" ) const ( // DefaultMaxBodyBytes 为请求正文的缺省上限,单位字节。 DefaultMaxBodyBytes int64 = 4 << 20 bodyCacheKey = "ginframework:request_body" codeBodyContext = 900101 codeBodyRead = 900102 codeBodyLarge = 900103 ) // ReadBodyWithLimit 有界读取并恢复 Request.Body,重复读取使用当前请求的缓存。 // 入参:ctx 为当前 Gin 请求,limit 为上限,非正值使用默认上限。 // 返回:正文副本视图;失败保留读取错误或 http.MaxBytesError 原因链。 func ReadBodyWithLimit(ctx *gin.Context, limit int64) ([]byte, error) { if ctx == nil || ctx.Request == nil { return nil, fault.WrapContext(contextOf(ctx), codeBodyContext, "validate request body context failed", errors.New("request context is missing")) } if limit <= 0 { limit = DefaultMaxBodyBytes } if limit == 1<<63-1 { return nil, fault.WrapContext(contextOf(ctx), codeBodyLarge, "validate request body limit failed", errors.New("body limit exceeds supported range")) } if cached, exists := ctx.Get(bodyCacheKey); exists { body := cached.([]byte) if int64(len(body)) > limit { return nil, fault.WrapContext(contextOf(ctx), codeBodyLarge, "validate request body size failed", &http.MaxBytesError{Limit: limit}) } ctx.Request.Body = io.NopCloser(bytes.NewReader(body)) return body, nil } if ctx.Request.Body == nil { return nil, nil } original := ctx.Request.Body body, err := io.ReadAll(io.LimitReader(original, limit+1)) // net/http 仍会关闭请求正文,此处提前释放已消费的原始 Reader。 _ = original.Close() ctx.Request.Body = io.NopCloser(bytes.NewReader(body)) if err != nil { return nil, fault.WrapContext(contextOf(ctx), codeBodyRead, "read request body failed", err) } if int64(len(body)) > limit { return nil, fault.WrapContext(contextOf(ctx), codeBodyLarge, "validate request body size failed", &http.MaxBytesError{Limit: limit}) } ctx.Set(bodyCacheKey, body) return body, nil }