Files
ginframework/http/trusted_fields.go
2026-11-28 02:51:21 -08:00

82 lines
3.4 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package http
import (
"errors"
"fmt"
"reflect"
"sort"
failure "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure"
"github.com/gin-gonic/gin"
)
// InjectTrustedFields 为原生 Gin Handler 注入可信公共字段,与 Server 的 Controller 共用赋值流程。
// 入参:ctx 必须含有效 Request;receiver 为非 nil 的可写结构体指针;rules 按 Go 字段名提供可信读取函数。
// 返回:表单、字段或读取错误,保留原因链;成功返回 nil。
// 缺失或歧义字段跳过;规则按名称排序,按需分配匿名嵌入指针。
// 每个匹配字段读取前清零,nil 返回表示保持零值;失败后不得继续使用该表单,已注入字段不会回滚。
// 调用方须保证调用期间独占表单,规则 map 不被并发修改;绑定和默认值在调用前完成,校验在成功后执行一次。
func InjectTrustedFields(ctx *gin.Context, receiver any, rules map[string]TrustedField) error {
form := reflect.ValueOf(receiver)
for form.IsValid() && form.Kind() == reflect.Ptr {
if form.IsNil() {
break
}
form = form.Elem()
}
if !form.IsValid() || form.Kind() != reflect.Struct || !form.CanSet() {
return failure.WrapContext(ctx.Request.Context(), codeTrustedForm, "validate trusted form failed", errors.New("trusted form must be a writable non-nil struct pointer"))
}
names := make([]string, 0, len(rules))
for name := range rules {
names = append(names, name)
}
sort.Strings(names)
return injectTrustedFields(ctx, form, rules, names)
}
// injectTrustedFields 对可写 Form 执行有序覆盖,供原生 Controller 与显式注入共同使用。
// 入参:ctx 含有效 Request;form 为已校验的可写结构体;rules 为可信读取函数;names 为排序后的规则名。
// 返回:字段不可写、规则为空、读取及类型错误;字段不存在时不执行对应读取函数。
func injectTrustedFields(ctx *gin.Context, form reflect.Value, rules map[string]TrustedField, names []string) error {
for _, name := range names {
definition, exists := form.Type().FieldByName(name)
if !exists {
continue
}
field := form
for _, index := range definition.Index {
if field.Kind() == reflect.Ptr {
if field.IsNil() {
if !field.CanSet() {
return failure.WrapContext(ctx.Request.Context(), codeInject, "resolve trusted field failed", fmt.Errorf("%s: embedded field is not writable", name))
}
field.Set(reflect.New(field.Type().Elem()))
}
field = field.Elem()
}
field = field.Field(index)
}
if !field.CanSet() {
return failure.WrapContext(ctx.Request.Context(), codeInject, "resolve trusted field failed", fmt.Errorf("%s: trusted field is not writable", name))
}
field.SetZero()
if rules[name] == nil {
return failure.WrapContext(ctx.Request.Context(), codeTrustedRule, "validate trusted field rule failed", fmt.Errorf("%s: trusted field callback is required", name))
}
value, err := rules[name](ctx)
if err != nil {
return failure.WrapContext(ctx.Request.Context(), codeTrustedRead, "read trusted field failed", err)
}
if value == nil {
continue
}
source := reflect.ValueOf(value)
if !source.Type().AssignableTo(field.Type()) {
return failure.WrapContext(ctx.Request.Context(), codeTrustedType, "assign trusted field failed", fmt.Errorf("%s: trusted field type mismatch", name))
}
field.Set(source)
}
return nil
}