381 lines
15 KiB
Go
381 lines
15 KiB
Go
package request
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"mime"
|
|
"mime/multipart"
|
|
"net/http"
|
|
"net/url"
|
|
"reflect"
|
|
"strings"
|
|
|
|
fault "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/gin-gonic/gin/binding"
|
|
"github.com/mcuadros/go-defaults"
|
|
)
|
|
|
|
var (
|
|
// ErrUnsupportedMediaType 表示请求 Body 使用了框架未支持的 Content-Type。
|
|
ErrUnsupportedMediaType = errors.New("unsupported request media type")
|
|
fileHeaderType = reflect.TypeOf(multipart.FileHeader{})
|
|
fileHeaderPointerType = reflect.TypeOf((*multipart.FileHeader)(nil))
|
|
)
|
|
|
|
// ParseOption 是单次请求绑定的可选配置。
|
|
type ParseOption struct {
|
|
MaxBodyBytes int64 `dc:"允许读取的请求正文最大字节数" json:"max_body_bytes"`
|
|
}
|
|
|
|
// ParseOptionFunc 修改单次请求绑定配置。
|
|
type ParseOptionFunc func(*ParseOption)
|
|
|
|
// WithMaxBodyBytes 设置当前路由允许读取的最大 Body 字节数。
|
|
//
|
|
// 入参:
|
|
// - maxBodyBytes:允许读取的请求正文最大字节数。
|
|
//
|
|
// 返回:
|
|
// - 返回值 1:绑定选项:只修改当前请求允许读取的正文大小。
|
|
func WithMaxBodyBytes(maxBodyBytes int64) ParseOptionFunc {
|
|
return func(option *ParseOption) {
|
|
option.MaxBodyBytes = maxBodyBytes
|
|
}
|
|
}
|
|
|
|
// form 提供分阶段绑定和最终校验能力。
|
|
type form struct{}
|
|
|
|
// Parse 保留原有的一站式 API:绑定、设置默认值并执行校验。
|
|
//
|
|
// 入参:
|
|
// - ctx:当前可信请求或内部调用上下文。
|
|
// - receiver:需要写入绑定结果的具体结构体指针。
|
|
// - optionList:由启动调用方提供的选项覆盖函数。
|
|
//
|
|
// 返回:
|
|
// - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。
|
|
func (formInstance *form) Parse(ctx *gin.Context, receiver any, optionList ...ParseOptionFunc) (resultError error) {
|
|
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.ValidateContext(contextOf(ctx), receiver)
|
|
}
|
|
|
|
// Bind 按 URI → Query → Body 的顺序绑定请求参数,但不设置默认值或执行校验。
|
|
//
|
|
// 入参:
|
|
// - ctx:当前可信请求或内部调用上下文。
|
|
// - receiver:需要写入绑定结果的具体结构体指针。
|
|
// - optionList:由启动调用方提供的选项覆盖函数。
|
|
//
|
|
// 返回:
|
|
// - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。
|
|
func (formInstance *form) Bind(ctx *gin.Context, receiver any, optionList ...ParseOptionFunc) (resultError error) {
|
|
defer fault.CaptureContext(contextOf(ctx), &resultError, CodeFormBind5, "bind failed")
|
|
|
|
if ctx == nil || ctx.Request == nil {
|
|
return fault.WrapContext(contextOf(ctx), CodeFormBind1, "bind failed", errors.New("invalid gin request context"))
|
|
}
|
|
if err := validateReceiver(contextOf(ctx), receiver); err != nil {
|
|
return err
|
|
}
|
|
option := buildParseOption(optionList...)
|
|
|
|
if err := bindURI(ctx, receiver); err != nil {
|
|
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.WrapContext(contextOf(ctx), CodeFormBind3, "bind failed", fmt.Errorf("bind query parameters: %w", err))
|
|
}
|
|
|
|
method := strings.ToUpper(ctx.Request.Method)
|
|
switch method {
|
|
case http.MethodGet, http.MethodHead, http.MethodOptions:
|
|
// 这些方法只消费 URI 和 Query,Body 不参与覆盖。
|
|
return nil
|
|
case http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete:
|
|
return formInstance.bindBody(ctx, receiver, option.MaxBodyBytes)
|
|
default:
|
|
return fault.WrapContext(contextOf(ctx), CodeFormBind4, "bind failed", fmt.Errorf("%s: request method is not supported", method))
|
|
}
|
|
}
|
|
|
|
// Validate 在所有参数来源、默认值和公共参数注入完成后,使用 Gin 全局校验器执行一次最终校验。
|
|
//
|
|
// 入参:
|
|
// - receiver:需要写入绑定结果的具体结构体指针。
|
|
//
|
|
// 返回:
|
|
// - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。
|
|
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
|
|
}
|
|
requestValidatorLock.RLock()
|
|
defer requestValidatorLock.RUnlock()
|
|
err := binding.Validator.ValidateStruct(receiver)
|
|
return validationResult(contextOf(ctx), receiver, err)
|
|
}
|
|
|
|
// bindBody 按请求媒体类型绑定正文,保留正文缓存与大小限制。
|
|
//
|
|
// 入参:
|
|
// - ctx:当前可信请求或内部调用上下文。
|
|
// - receiver:需要写入绑定结果的具体结构体指针。
|
|
// - maxBodyBytes:允许读取的请求正文最大字节数。
|
|
//
|
|
// 返回:
|
|
// - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。
|
|
func (formInstance *form) bindBody(ctx *gin.Context, receiver any, maxBodyBytes int64) (resultError error) {
|
|
defer fault.CaptureContext(contextOf(ctx), &resultError, CodeFormBindBody10, "bind body failed")
|
|
|
|
bodyData, err := ReadBodyWithLimit(ctx, maxBodyBytes)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if len(bodyData) == 0 {
|
|
return nil
|
|
}
|
|
|
|
contentType := ctx.GetHeader("Content-Type")
|
|
mediaType, _, err := mime.ParseMediaType(contentType)
|
|
if err != nil {
|
|
return fault.WrapContext(contextOf(ctx), CodeFormBindBody1, "bind body failed", fmt.Errorf("%w: invalid Content-Type %q: %v", ErrUnsupportedMediaType, contentType, err))
|
|
}
|
|
mediaType = strings.ToLower(mediaType)
|
|
|
|
switch {
|
|
case mediaType == "application/json" || strings.HasSuffix(mediaType, "+json"):
|
|
decoder := json.NewDecoder(bytes.NewReader(bodyData))
|
|
if binding.EnableDecoderUseNumber {
|
|
decoder.UseNumber()
|
|
}
|
|
if binding.EnableDecoderDisallowUnknownFields {
|
|
decoder.DisallowUnknownFields()
|
|
}
|
|
if err = decoder.Decode(receiver); err != nil {
|
|
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.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.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.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.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.WrapContext(contextOf(ctx), CodeFormBindBody7, "bind body failed", fmt.Errorf("bind multipart values: %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.WrapContext(contextOf(ctx), CodeFormBindBody9, "bind body failed", fmt.Errorf("%w: %s", ErrUnsupportedMediaType, mediaType))
|
|
}
|
|
}
|
|
|
|
// buildParseOption 创建当前绑定操作的独立选项并应用显式覆盖。
|
|
//
|
|
// 入参:
|
|
// - optionList:由启动调用方提供的选项覆盖函数。
|
|
//
|
|
// 返回:
|
|
// - 返回值 1:绑定配置:应用显式覆盖后的单次请求选项。
|
|
func buildParseOption(optionList ...ParseOptionFunc) ParseOption {
|
|
option := ParseOption{
|
|
MaxBodyBytes: DefaultMaxBodyBytes,
|
|
}
|
|
for _, optionFunc := range optionList {
|
|
if optionFunc != nil {
|
|
optionFunc(&option)
|
|
}
|
|
}
|
|
if option.MaxBodyBytes <= 0 {
|
|
option.MaxBodyBytes = DefaultMaxBodyBytes
|
|
}
|
|
return option
|
|
}
|
|
|
|
// validateReceiver 检查请求绑定目标是否为可写的非空结构体指针。
|
|
//
|
|
// 入参:
|
|
// - ctx:当前可信请求或内部调用上下文。
|
|
// - receiver:需要写入绑定结果的具体结构体指针。
|
|
//
|
|
// 返回:
|
|
// - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。
|
|
func validateReceiver(ctx context.Context, receiver any) (resultError error) {
|
|
defer fault.CaptureContext(contextOf(ctx), &resultError, CodeValidateReceiver3, "validate receiver failed")
|
|
|
|
if receiver == 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.WrapContext(contextOf(ctx), CodeValidateReceiver2, "validate receiver failed", fmt.Errorf("request receiver must be a non-nil pointer, got %T", receiver))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// bindURI 将路由参数绑定到表单声明的 URI 字段。
|
|
//
|
|
// 入参:
|
|
// - ctx:当前可信请求或内部调用上下文。
|
|
// - receiver:需要写入绑定结果的具体结构体指针。
|
|
//
|
|
// 返回:
|
|
// - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。
|
|
func bindURI(ctx *gin.Context, receiver any) (resultError error) {
|
|
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 {
|
|
uriValues[param.Key] = []string{param.Value}
|
|
}
|
|
return binding.MapFormWithTag(receiver, uriValues, "uri")
|
|
}
|
|
|
|
// bindMultipartFiles 将常见 multipart.FileHeader 字段绑定到请求结构体。
|
|
//
|
|
// 入参:
|
|
// - ctx:当前可信请求或内部调用上下文。
|
|
// - receiver:需要写入绑定结果的具体结构体指针。
|
|
// - files:本次上传解析得到的文件头列表。
|
|
//
|
|
// 返回:
|
|
// - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。
|
|
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(ctx, reflect.ValueOf(receiver), files)
|
|
}
|
|
|
|
// walkMultipartFields 递归绑定表单字段及文件,保留嵌入和可选字段语义。
|
|
//
|
|
// 入参:
|
|
// - ctx:当前可信请求或内部调用上下文。
|
|
// - value:需要按当前方法约定检查或转换的值。
|
|
// - files:本次上传解析得到的文件头列表。
|
|
//
|
|
// 返回:
|
|
// - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。
|
|
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(ctx, value.Elem(), files)
|
|
}
|
|
if value.Kind() != reflect.Struct {
|
|
return nil
|
|
}
|
|
|
|
valueType := value.Type()
|
|
for fieldIndex := 0; fieldIndex < value.NumField(); fieldIndex++ {
|
|
structField := valueType.Field(fieldIndex)
|
|
fieldValue := value.Field(fieldIndex)
|
|
if structField.PkgPath != "" && !structField.Anonymous {
|
|
continue
|
|
}
|
|
fieldName := strings.Split(structField.Tag.Get("form"), ",")[0]
|
|
if fieldName == "-" {
|
|
continue
|
|
}
|
|
if fieldName == "" {
|
|
fieldName = structField.Name
|
|
}
|
|
if fileList := files[fieldName]; len(fileList) > 0 {
|
|
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(ctx, fieldValue, files); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// setMultipartFileValue 按目标字段类型写入单个或多个上传文件。
|
|
//
|
|
// 入参:
|
|
// - ctx:当前可信请求或内部调用上下文。
|
|
// - fieldValue:需要绑定或检查的可写字段反射值。
|
|
// - files:本次上传解析得到的文件头列表。
|
|
//
|
|
// 返回:
|
|
// - 返回值 1:错误:成功返回 nil;失败保留所属场景及原始原因链。
|
|
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.WrapContext(contextOf(ctx), CodeSetMultipartFileValue1, "set multipart file value failed", errors.New("field cannot be set"))
|
|
}
|
|
switch fieldValue.Type() {
|
|
case fileHeaderPointerType:
|
|
fieldValue.Set(reflect.ValueOf(files[0]))
|
|
return nil
|
|
case fileHeaderType:
|
|
fieldValue.Set(reflect.ValueOf(*files[0]))
|
|
return nil
|
|
}
|
|
if fieldValue.Kind() == reflect.Slice && fieldValue.Type().Elem() == fileHeaderPointerType {
|
|
fileSlice := reflect.MakeSlice(fieldValue.Type(), len(files), len(files))
|
|
for index, file := range files {
|
|
fileSlice.Index(index).Set(reflect.ValueOf(file))
|
|
}
|
|
fieldValue.Set(fileSlice)
|
|
return nil
|
|
}
|
|
return fault.WrapContext(contextOf(ctx), CodeSetMultipartFileValue2, "set multipart file value failed", fmt.Errorf("unsupported multipart file type %s", fieldValue.Type()))
|
|
}
|
|
|
|
// indirectKind 沿指针类型解析实际字段种类。
|
|
//
|
|
// 入参:
|
|
// - valueType:参与绑定的目标字段类型。
|
|
//
|
|
// 返回:
|
|
// - 返回值 1:实际字段种类:指针已展开。
|
|
func indirectKind(valueType reflect.Type) reflect.Kind {
|
|
for valueType.Kind() == reflect.Ptr {
|
|
valueType = valueType.Elem()
|
|
}
|
|
return valueType.Kind()
|
|
}
|