193 lines
6.6 KiB
Go
193 lines
6.6 KiB
Go
package request
|
||
|
||
import (
|
||
"context"
|
||
"errors"
|
||
"reflect"
|
||
"regexp"
|
||
"strings"
|
||
|
||
failure "git.zhangdeman.cn/zhangdeman/ginframework/internal/failure"
|
||
"github.com/go-playground/validator/v10"
|
||
)
|
||
|
||
var (
|
||
namespaceIndices = regexp.MustCompile(`\[[^\]]*\]`)
|
||
)
|
||
|
||
// FieldError 是允许公开的字段约束提示,不包含原始值或校验参数。
|
||
type FieldError struct {
|
||
Field string `json:"field" dc:"声明中的公开字段路径,集合下标统一为 []"`
|
||
Rule string `json:"rule" dc:"服务端声明的校验规则名,不包含参数或输入值"`
|
||
Message string `json:"message" dc:"安全提示,可由字段静态 err 标签指定"`
|
||
}
|
||
|
||
// ValidationDetails 是统一 400 响应中允许公开的字段错误数据。
|
||
type ValidationDetails struct {
|
||
Fields []FieldError `json:"fields" dc:"按校验器顺序排列的安全字段错误"`
|
||
}
|
||
|
||
// ValidationError 保留原生 validator 原因链及独立的公开提示。
|
||
type ValidationError struct {
|
||
Fields []FieldError `json:"fields" dc:"不包含凭据或客户端值的字段级提示"`
|
||
cause error `dc:"已在可信调用上下文分类记录的原始错误链"`
|
||
}
|
||
|
||
// Error 返回安全摘要。
|
||
// 返回:固定的校验失败说明,不输出原始值或内部结构体命名。
|
||
func (e *ValidationError) Error() string { return "request validation failed" }
|
||
|
||
// Unwrap 保留 validator 的错误原因。
|
||
// 返回:已记录的内部场景错误,支持继续 errors.As 到原生 ValidationErrors。
|
||
func (e *ValidationError) Unwrap() error { return e.cause }
|
||
|
||
// Code 返回所属校验失败场景码。
|
||
// 返回:内部场景码,不作为公开业务错误码。
|
||
func (e *ValidationError) Code() int { return CodeFormValidate1 }
|
||
|
||
// validationResult 在校验源头分类并提取静态声明中的安全字段描述。
|
||
// 入参:ctx 为标准上下文,receiver 为校验目标,err 为原生校验结果。
|
||
// 返回:成功时为 nil,字段失败为 ValidationError,其他失败保留原始原因。
|
||
func validationResult(ctx context.Context, receiver any, err error) error {
|
||
if err == nil {
|
||
return nil
|
||
}
|
||
classified := failure.WrapContext(ctx, CodeFormValidate1, "validate request fields failed", err)
|
||
public := ValidationFields(receiver, err, ValidationOptions{})
|
||
if public == nil {
|
||
return classified
|
||
}
|
||
for index := range public {
|
||
if public[index].Message == "" {
|
||
public[index].Message = validationMessage(public[index].Rule)
|
||
}
|
||
}
|
||
return &ValidationError{Fields: public, cause: classified}
|
||
}
|
||
|
||
// fieldDescription 只沿静态类型寻找公开名称,屏蔽动态 Map 键及集合下标。
|
||
// 入参:root 为 Form 类型,namespace 为校验器返回的字段路径,options 为文案与字段名策略。
|
||
// 返回:公开字段路径和字段 err 标签;无法映射或显式隐藏时使用 request 与通用提示。
|
||
func fieldDescription(root reflect.Type, namespace string, options ValidationOptions) (string, string) {
|
||
for root != nil && root.Kind() == reflect.Ptr {
|
||
root = root.Elem()
|
||
}
|
||
if root == nil || root.Kind() != reflect.Struct {
|
||
return "request", ""
|
||
}
|
||
namespace = strings.TrimPrefix(namespace, root.Name()+".")
|
||
parts := strings.Split(namespaceIndices.ReplaceAllString(namespace, "[]"), ".")
|
||
var (
|
||
names []string
|
||
message string
|
||
)
|
||
current := root
|
||
for _, part := range parts {
|
||
for current.Kind() == reflect.Ptr {
|
||
current = current.Elem()
|
||
}
|
||
if current.Kind() != reflect.Struct {
|
||
return "request", ""
|
||
}
|
||
identifier := strings.SplitN(part, "[", 2)[0]
|
||
field, ok := current.FieldByName(identifier)
|
||
if !ok || field.PkgPath != "" && !field.Anonymous {
|
||
return "request", ""
|
||
}
|
||
suffix := strings.TrimPrefix(part, identifier)
|
||
if strings.ReplaceAll(suffix, "[]", "") != "" {
|
||
return "request", ""
|
||
}
|
||
label := ""
|
||
for _, tag := range []string{"json", "form", "uri"} {
|
||
candidate := strings.SplitN(field.Tag.Get(tag), ",", 2)[0]
|
||
if candidate == "-" {
|
||
return "request", ""
|
||
}
|
||
if candidate != "" {
|
||
label = candidate
|
||
break
|
||
}
|
||
}
|
||
if label == "" && !field.Anonymous {
|
||
label = field.Name
|
||
}
|
||
if label != "" {
|
||
names = append(names, label+suffix)
|
||
}
|
||
current = field.Type
|
||
for i := 0; i < strings.Count(suffix, "[]"); i++ {
|
||
for current.Kind() == reflect.Ptr {
|
||
current = current.Elem()
|
||
}
|
||
switch current.Kind() {
|
||
case reflect.Map, reflect.Array, reflect.Slice:
|
||
current = current.Elem()
|
||
default:
|
||
return "request", ""
|
||
}
|
||
}
|
||
message = field.Tag.Get(options.MessageTag)
|
||
}
|
||
if len(names) == 0 {
|
||
return "request", ""
|
||
}
|
||
if options.LeafNames {
|
||
return names[len(names)-1], message
|
||
}
|
||
return strings.Join(names, "."), message
|
||
}
|
||
|
||
// validationMessage 将常见规则转成不暴露输入或限制参数的安全说明。
|
||
// 入参:rule 为服务端校验规则名。
|
||
// 返回:英文缺省提示,自定义规则返回通用提示。
|
||
func validationMessage(rule string) string {
|
||
switch rule {
|
||
case "required", "required_if", "required_with", "required_without":
|
||
return "This field is required"
|
||
case "email":
|
||
return "Invalid email address"
|
||
case "min", "gte", "gt":
|
||
return "Value is below the allowed minimum"
|
||
case "max", "lte", "lt":
|
||
return "Value exceeds the allowed maximum"
|
||
case "len":
|
||
return "Invalid length"
|
||
case "oneof":
|
||
return "Value is not allowed"
|
||
default:
|
||
return "Invalid value"
|
||
}
|
||
}
|
||
|
||
// ValidationOptions 描述静态校验字段提取,不改变校验规则或执行次数。
|
||
type ValidationOptions struct {
|
||
MessageTag string `json:"message_tag" dc:"静态提示标签名,空使用 err"`
|
||
LeafNames bool `json:"leaf_names" dc:"仅返回最后一级静态字段名,默认返回完整公开路径"`
|
||
}
|
||
|
||
// ValidationFields 提取 validator 原因链中的安全字段描述,不执行校验、记录日志或改写错误。
|
||
// 入参:receiver 为原表单或允许 nil,rawError 为允许 nil 的原始/包装校验错误,options 为静态标签策略。
|
||
// 返回:非校验错误返回 nil;校验错误返回独立列表,Message 仅取静态标签,无标签时为空。
|
||
// 路径只从静态类型获得,集合索引与 Map 键隐藏,无法映射或 json/form/uri 显式隐藏时使用 request。
|
||
func ValidationFields(receiver any, rawError error, options ValidationOptions) []FieldError {
|
||
if rawError == nil {
|
||
return nil
|
||
}
|
||
var (
|
||
fields validator.ValidationErrors
|
||
)
|
||
if !errors.As(rawError, &fields) {
|
||
return nil
|
||
}
|
||
if options.MessageTag == "" {
|
||
options.MessageTag = "err"
|
||
}
|
||
result := make([]FieldError, 0, len(fields))
|
||
for _, field := range fields {
|
||
name, message := fieldDescription(reflect.TypeOf(receiver), field.StructNamespace(), options)
|
||
result = append(result, FieldError{Field: name, Rule: field.Tag(), Message: message})
|
||
}
|
||
return result
|
||
}
|