增加安全字段校验提示、请求预算和就绪/存活探针, 让绑定、数据库、Redis 和出站响应解码保留可信诊断上下文。 补充完整应用装配及逆序清理示例,同步接入和迁移文档。 验证:make verify、make race-check 全部通过。 BREAKING CHANGE: 普通 Controller 默认启用 30 秒协作式请求预算, 可用 request_timeout_ms: 0 或 max-exec-time:"0" 关闭; 字段校验失败的 400 响应增加安全字段明细。
This commit is contained in:
1 parent
b4c3ac622c
commit
3196e45a01
22 files changed
+1294
-79
No files matched your search
+51
-41
@@ -2,6 +2,7 @@ package request
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -61,13 +62,13 @@ type form struct{}
|
||||
// 返回:
|
||||
// - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。
|
||||
func (formInstance *form) Parse(ctx *gin.Context, receiver any, optionList ...ParseOptionFunc) (resultError error) {
|
||||
defer fault.Capture(&resultError, CodeFormParse1, "parse failed")
|
||||
defer fault.CaptureContext(contextOf(ctx), &resultError, CodeFormParse1, "parse failed")
|
||||
|
||||
if err := formInstance.Bind(ctx, receiver, optionList...); err != nil {
|
||||
return err
|
||||
}
|
||||
defaults.SetDefaults(receiver)
|
||||
return formInstance.Validate(receiver)
|
||||
return formInstance.ValidateContext(contextOf(ctx), receiver)
|
||||
}
|
||||
|
||||
// Bind 按 URI → Query → Body 的顺序绑定请求参数,但不设置默认值或执行校验。
|
||||
@@ -80,21 +81,21 @@ func (formInstance *form) Parse(ctx *gin.Context, receiver any, optionList ...Pa
|
||||
// 返回:
|
||||
// - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。
|
||||
func (formInstance *form) Bind(ctx *gin.Context, receiver any, optionList ...ParseOptionFunc) (resultError error) {
|
||||
defer fault.Capture(&resultError, CodeFormBind5, "bind failed")
|
||||
defer fault.CaptureContext(contextOf(ctx), &resultError, CodeFormBind5, "bind failed")
|
||||
|
||||
if ctx == nil || ctx.Request == nil {
|
||||
return fault.Wrap(CodeFormBind1, "bind failed", errors.New("invalid gin request context"))
|
||||
return fault.WrapContext(contextOf(ctx), CodeFormBind1, "bind failed", errors.New("invalid gin request context"))
|
||||
}
|
||||
if err := validateReceiver(receiver); err != nil {
|
||||
if err := validateReceiver(contextOf(ctx), receiver); err != nil {
|
||||
return err
|
||||
}
|
||||
option := buildParseOption(optionList...)
|
||||
|
||||
if err := bindURI(ctx, receiver); err != nil {
|
||||
return fault.Wrap(CodeFormBind2, "bind failed", fmt.Errorf("bind URI parameters: %w", err))
|
||||
return fault.WrapContext(contextOf(ctx), CodeFormBind2, "bind failed", fmt.Errorf("bind URI parameters: %w", err))
|
||||
}
|
||||
if err := binding.MapFormWithTag(receiver, ctx.Request.URL.Query(), "form"); err != nil {
|
||||
return fault.Wrap(CodeFormBind3, "bind failed", fmt.Errorf("bind query parameters: %w", err))
|
||||
return fault.WrapContext(contextOf(ctx), CodeFormBind3, "bind failed", fmt.Errorf("bind query parameters: %w", err))
|
||||
}
|
||||
|
||||
method := strings.ToUpper(ctx.Request.Method)
|
||||
@@ -105,7 +106,7 @@ func (formInstance *form) Bind(ctx *gin.Context, receiver any, optionList ...Par
|
||||
case http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete:
|
||||
return formInstance.bindBody(ctx, receiver, option.MaxBodyBytes)
|
||||
default:
|
||||
return fault.Wrap(CodeFormBind4, "bind failed", fmt.Errorf("%s: request method is not supported", method))
|
||||
return fault.WrapContext(contextOf(ctx), CodeFormBind4, "bind failed", fmt.Errorf("%s: request method is not supported", method))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,16 +117,21 @@ func (formInstance *form) Bind(ctx *gin.Context, receiver any, optionList ...Par
|
||||
//
|
||||
// 返回:
|
||||
// - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。
|
||||
func (*form) Validate(receiver any) (resultError error) {
|
||||
defer fault.Capture(&resultError, CodeFormValidate1, "validate failed")
|
||||
func (f *form) Validate(receiver any) error {
|
||||
return f.ValidateContext(context.Background(), receiver)
|
||||
}
|
||||
|
||||
// ValidateContext 使用可信调用上下文执行一次最终校验,返回安全的字段级错误。
|
||||
// 入参:ctx 为标准上下文,receiver 为绑定及可信注入完成的 Form。
|
||||
// 返回:字段约束失败返回 ValidationError;错误链与源头日志保留原始校验原因。
|
||||
func (*form) ValidateContext(ctx context.Context, receiver any) error {
|
||||
if binding.Validator == nil {
|
||||
return nil
|
||||
}
|
||||
// 与 RegisterValidation 共用读写锁,保证运行期规则注册不会和请求校验并发修改 validator 缓存。
|
||||
requestValidatorLock.RLock()
|
||||
defer requestValidatorLock.RUnlock()
|
||||
return binding.Validator.ValidateStruct(receiver)
|
||||
err := binding.Validator.ValidateStruct(receiver)
|
||||
return validationResult(contextOf(ctx), receiver, err)
|
||||
}
|
||||
|
||||
// bindBody 按请求媒体类型绑定正文,保留正文缓存与大小限制。
|
||||
@@ -138,7 +144,7 @@ func (*form) Validate(receiver any) (resultError error) {
|
||||
// 返回:
|
||||
// - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。
|
||||
func (formInstance *form) bindBody(ctx *gin.Context, receiver any, maxBodyBytes int64) (resultError error) {
|
||||
defer fault.Capture(&resultError, CodeFormBindBody10, "bind body failed")
|
||||
defer fault.CaptureContext(contextOf(ctx), &resultError, CodeFormBindBody10, "bind body failed")
|
||||
|
||||
bodyData, err := ReadBodyWithLimit(ctx, maxBodyBytes)
|
||||
if err != nil {
|
||||
@@ -151,7 +157,7 @@ func (formInstance *form) bindBody(ctx *gin.Context, receiver any, maxBodyBytes
|
||||
contentType := ctx.GetHeader("Content-Type")
|
||||
mediaType, _, err := mime.ParseMediaType(contentType)
|
||||
if err != nil {
|
||||
return fault.Wrap(CodeFormBindBody1, "bind body failed", fmt.Errorf("%w: invalid Content-Type %q: %v", ErrUnsupportedMediaType, contentType, err))
|
||||
return fault.WrapContext(contextOf(ctx), CodeFormBindBody1, "bind body failed", fmt.Errorf("%w: invalid Content-Type %q: %v", ErrUnsupportedMediaType, contentType, err))
|
||||
}
|
||||
mediaType = strings.ToLower(mediaType)
|
||||
|
||||
@@ -165,35 +171,35 @@ func (formInstance *form) bindBody(ctx *gin.Context, receiver any, maxBodyBytes
|
||||
decoder.DisallowUnknownFields()
|
||||
}
|
||||
if err = decoder.Decode(receiver); err != nil {
|
||||
return fault.Wrap(CodeFormBindBody2, "bind body failed", fmt.Errorf("decode JSON body: %w", err))
|
||||
return fault.WrapContext(contextOf(ctx), CodeFormBindBody2, "bind body failed", fmt.Errorf("decode JSON body: %w", err))
|
||||
}
|
||||
if err = decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
|
||||
return fault.Wrap(CodeFormBindBody3, "bind body failed", errors.New("decode JSON body: multiple JSON values are not allowed"))
|
||||
return fault.WrapContext(contextOf(ctx), CodeFormBindBody3, "bind body failed", errors.New("decode JSON body: multiple JSON values are not allowed"))
|
||||
}
|
||||
return nil
|
||||
case mediaType == "application/x-www-form-urlencoded":
|
||||
values, parseErr := url.ParseQuery(string(bodyData))
|
||||
if parseErr != nil {
|
||||
return fault.Wrap(CodeFormBindBody4, "bind body failed", fmt.Errorf("parse form body: %w", parseErr))
|
||||
return fault.WrapContext(contextOf(ctx), CodeFormBindBody4, "bind body failed", fmt.Errorf("parse form body: %w", parseErr))
|
||||
}
|
||||
if err = binding.MapFormWithTag(receiver, values, "form"); err != nil {
|
||||
return fault.Wrap(CodeFormBindBody5, "bind body failed", fmt.Errorf("bind form body: %w", err))
|
||||
return fault.WrapContext(contextOf(ctx), CodeFormBindBody5, "bind body failed", fmt.Errorf("bind form body: %w", err))
|
||||
}
|
||||
return nil
|
||||
case mediaType == "multipart/form-data":
|
||||
// ReadBodyWithLimit 已恢复 Request.Body,这里可继续交给 net/http 按 boundary 解析。
|
||||
if err = ctx.Request.ParseMultipartForm(maxBodyBytes); err != nil {
|
||||
return fault.Wrap(CodeFormBindBody6, "bind body failed", fmt.Errorf("parse multipart body: %w", err))
|
||||
return fault.WrapContext(contextOf(ctx), CodeFormBindBody6, "bind body failed", fmt.Errorf("parse multipart body: %w", err))
|
||||
}
|
||||
if err = binding.MapFormWithTag(receiver, ctx.Request.MultipartForm.Value, "form"); err != nil {
|
||||
return fault.Wrap(CodeFormBindBody7, "bind body failed", fmt.Errorf("bind multipart values: %w", err))
|
||||
return fault.WrapContext(contextOf(ctx), CodeFormBindBody7, "bind body failed", fmt.Errorf("bind multipart values: %w", err))
|
||||
}
|
||||
if err = bindMultipartFiles(receiver, ctx.Request.MultipartForm.File); err != nil {
|
||||
return fault.Wrap(CodeFormBindBody8, "bind body failed", fmt.Errorf("bind multipart files: %w", err))
|
||||
if err = bindMultipartFiles(contextOf(ctx), receiver, ctx.Request.MultipartForm.File); err != nil {
|
||||
return fault.WrapContext(contextOf(ctx), CodeFormBindBody8, "bind body failed", fmt.Errorf("bind multipart files: %w", err))
|
||||
}
|
||||
return nil
|
||||
default:
|
||||
return fault.Wrap(CodeFormBindBody9, "bind body failed", fmt.Errorf("%w: %s", ErrUnsupportedMediaType, mediaType))
|
||||
return fault.WrapContext(contextOf(ctx), CodeFormBindBody9, "bind body failed", fmt.Errorf("%w: %s", ErrUnsupportedMediaType, mediaType))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -222,19 +228,20 @@ func buildParseOption(optionList ...ParseOptionFunc) ParseOption {
|
||||
// validateReceiver 检查请求绑定目标是否为可写的非空结构体指针。
|
||||
//
|
||||
// 入参:
|
||||
// - ctx:当前可信请求或内部调用上下文。
|
||||
// - receiver:需要写入绑定结果的具体结构体指针。
|
||||
//
|
||||
// 返回:
|
||||
// - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。
|
||||
func validateReceiver(receiver any) (resultError error) {
|
||||
defer fault.Capture(&resultError, CodeValidateReceiver3, "validate receiver failed")
|
||||
func validateReceiver(ctx context.Context, receiver any) (resultError error) {
|
||||
defer fault.CaptureContext(contextOf(ctx), &resultError, CodeValidateReceiver3, "validate receiver failed")
|
||||
|
||||
if receiver == nil {
|
||||
return fault.Wrap(CodeValidateReceiver1, "validate receiver failed", errors.New("request receiver cannot be nil"))
|
||||
return fault.WrapContext(contextOf(ctx), CodeValidateReceiver1, "validate receiver failed", errors.New("request receiver cannot be nil"))
|
||||
}
|
||||
value := reflect.ValueOf(receiver)
|
||||
if value.Kind() != reflect.Ptr || value.IsNil() || value.Elem().Kind() != reflect.Struct {
|
||||
return fault.Wrap(CodeValidateReceiver2, "validate receiver failed", fmt.Errorf("request receiver must be a non-nil pointer, got %T", receiver))
|
||||
return fault.WrapContext(contextOf(ctx), CodeValidateReceiver2, "validate receiver failed", fmt.Errorf("request receiver must be a non-nil pointer, got %T", receiver))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -248,7 +255,7 @@ func validateReceiver(receiver any) (resultError error) {
|
||||
// 返回:
|
||||
// - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。
|
||||
func bindURI(ctx *gin.Context, receiver any) (resultError error) {
|
||||
defer fault.Capture(&resultError, CodeBindURI1, "bind u r i failed")
|
||||
defer fault.CaptureContext(contextOf(ctx), &resultError, CodeBindURI1, "bind u r i failed")
|
||||
|
||||
uriValues := make(map[string][]string, len(ctx.Params))
|
||||
for _, param := range ctx.Params {
|
||||
@@ -260,34 +267,36 @@ func bindURI(ctx *gin.Context, receiver any) (resultError error) {
|
||||
// bindMultipartFiles 将常见 multipart.FileHeader 字段绑定到请求结构体。
|
||||
//
|
||||
// 入参:
|
||||
// - ctx:当前可信请求或内部调用上下文。
|
||||
// - receiver:需要写入绑定结果的具体结构体指针。
|
||||
// - files:本次上传解析得到的文件头列表。
|
||||
//
|
||||
// 返回:
|
||||
// - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。
|
||||
func bindMultipartFiles(receiver any, files map[string][]*multipart.FileHeader) (resultError error) {
|
||||
defer fault.Capture(&resultError, CodeBindMultipartFiles1, "bind multipart files failed")
|
||||
func bindMultipartFiles(ctx context.Context, receiver any, files map[string][]*multipart.FileHeader) (resultError error) {
|
||||
defer fault.CaptureContext(contextOf(ctx), &resultError, CodeBindMultipartFiles1, "bind multipart files failed")
|
||||
|
||||
return walkMultipartFields(reflect.ValueOf(receiver), files)
|
||||
return walkMultipartFields(ctx, reflect.ValueOf(receiver), files)
|
||||
}
|
||||
|
||||
// walkMultipartFields 递归绑定表单字段及文件,保留嵌入和可选字段语义。
|
||||
//
|
||||
// 入参:
|
||||
// - ctx:当前可信请求或内部调用上下文。
|
||||
// - value:需要按当前方法约定检查或转换的值。
|
||||
// - files:本次上传解析得到的文件头列表。
|
||||
//
|
||||
// 返回:
|
||||
// - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。
|
||||
func walkMultipartFields(value reflect.Value, files map[string][]*multipart.FileHeader) (resultError error) {
|
||||
defer fault.Capture(&resultError, CodeWalkMultipartFields2, "walk multipart fields failed")
|
||||
func walkMultipartFields(ctx context.Context, value reflect.Value, files map[string][]*multipart.FileHeader) (resultError error) {
|
||||
defer fault.CaptureContext(contextOf(ctx), &resultError, CodeWalkMultipartFields2, "walk multipart fields failed")
|
||||
|
||||
if value.Kind() == reflect.Ptr {
|
||||
if value.IsNil() {
|
||||
// 不为仅可能存在的文件字段创建业务对象;非 nil 的嵌套结构仍会继续绑定。
|
||||
return nil
|
||||
}
|
||||
return walkMultipartFields(value.Elem(), files)
|
||||
return walkMultipartFields(ctx, value.Elem(), files)
|
||||
}
|
||||
if value.Kind() != reflect.Struct {
|
||||
return nil
|
||||
@@ -308,13 +317,13 @@ func walkMultipartFields(value reflect.Value, files map[string][]*multipart.File
|
||||
fieldName = structField.Name
|
||||
}
|
||||
if fileList := files[fieldName]; len(fileList) > 0 {
|
||||
if err := setMultipartFileValue(fieldValue, fileList); err != nil {
|
||||
return fault.Wrap(CodeWalkMultipartFields1, "walk multipart fields failed", fmt.Errorf("field %s: %w", structField.Name, err))
|
||||
if err := setMultipartFileValue(ctx, fieldValue, fileList); err != nil {
|
||||
return fault.WrapContext(contextOf(ctx), CodeWalkMultipartFields1, "walk multipart fields failed", fmt.Errorf("field %s: %w", structField.Name, err))
|
||||
}
|
||||
continue
|
||||
}
|
||||
if structField.Anonymous || indirectKind(fieldValue.Type()) == reflect.Struct {
|
||||
if err := walkMultipartFields(fieldValue, files); err != nil {
|
||||
if err := walkMultipartFields(ctx, fieldValue, files); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -325,16 +334,17 @@ func walkMultipartFields(value reflect.Value, files map[string][]*multipart.File
|
||||
// setMultipartFileValue 按目标字段类型写入单个或多个上传文件。
|
||||
//
|
||||
// 入参:
|
||||
// - ctx:当前可信请求或内部调用上下文。
|
||||
// - fieldValue:需要绑定或检查的可写字段反射值。
|
||||
// - files:本次上传解析得到的文件头列表。
|
||||
//
|
||||
// 返回:
|
||||
// - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。
|
||||
func setMultipartFileValue(fieldValue reflect.Value, files []*multipart.FileHeader) (resultError error) {
|
||||
defer fault.Capture(&resultError, CodeSetMultipartFileValue3, "set multipart file value failed")
|
||||
func setMultipartFileValue(ctx context.Context, fieldValue reflect.Value, files []*multipart.FileHeader) (resultError error) {
|
||||
defer fault.CaptureContext(contextOf(ctx), &resultError, CodeSetMultipartFileValue3, "set multipart file value failed")
|
||||
|
||||
if !fieldValue.CanSet() {
|
||||
return fault.Wrap(CodeSetMultipartFileValue1, "set multipart file value failed", errors.New("field cannot be set"))
|
||||
return fault.WrapContext(contextOf(ctx), CodeSetMultipartFileValue1, "set multipart file value failed", errors.New("field cannot be set"))
|
||||
}
|
||||
switch fieldValue.Type() {
|
||||
case fileHeaderPointerType:
|
||||
@@ -352,7 +362,7 @@ func setMultipartFileValue(fieldValue reflect.Value, files []*multipart.FileHead
|
||||
fieldValue.Set(fileSlice)
|
||||
return nil
|
||||
}
|
||||
return fault.Wrap(CodeSetMultipartFileValue2, "set multipart file value failed", fmt.Errorf("unsupported multipart file type %s", fieldValue.Type()))
|
||||
return fault.WrapContext(contextOf(ctx), CodeSetMultipartFileValue2, "set multipart file value failed", fmt.Errorf("unsupported multipart file type %s", fieldValue.Type()))
|
||||
}
|
||||
|
||||
// indirectKind 沿指针类型解析实际字段种类。
|
||||
|
||||