可以使用gin框架的BindJSON方法将json字符串加载到struct中,然后使用反射获取struct中的tag,并验证字段值。

示例代码:

type User struct {
    Name     string `json:"name" binding:"required"`
    Age      int    `json:"age" binding:"required,min=18,max=60"`
    Email    string `json:"email" binding:"required,email"`
    Password string `json:"password" binding:"required,min=6"`
}

func CreateUser(c *gin.Context) {
    var user User
    if err := c.BindJSON(&user); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    // 使用反射获取struct中的tag,并验证字段值
    v := reflect.ValueOf(user)
    t := v.Type()
    for i := 0; i < v.NumField(); i++ {
        field := v.Field(i)
        tag := t.Field(i).Tag.Get("binding")
        if tag != "" {
            if err := validateField(field, tag); err != nil {
                c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
                return
            }
        }
    }

    // TODO: 创建用户
    c.JSON(http.StatusOK, gin.H{"message": "User created successfully"})
}

func validateField(field reflect.Value, tag string) error {
    switch tag {
    case "required":
        if field.Interface() == "" {
            return errors.New("field is required")
        }
    case "email":
        email := field.Interface().(string)
        if !strings.Contains(email, "@") {
            return errors.New("invalid email")
        }
    case "min":
        min, _ := strconv.Atoi(tag[4:])
        if field.Int() < int64(min) {
            return fmt.Errorf("field must be greater than or equal to %d", min)
        }
    case "max":
        max, _ := strconv.Atoi(tag[4:])
        if field.Int() > int64(max) {
            return fmt.Errorf("field must be less than or equal to %d", max)
        }
    }
    return nil
}

在上面的示例中,CreateUser函数使用BindJSON方法将json字符串加载到User结构体中。然后,使用反射获取User结构体中的每个字段,并根据其tag验证字段值。如果验证失败,则返回错误响应。如果所有字段都通过验证,则创建用户并返回成功响应。

gin框架将json字符串加载到struct并根据strcut中的tag验证字段值

原文地址: https://www.cveoy.top/t/topic/bYY6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录