go - 使用 Gin 框架验证 Golang 中的枚举

标签 go go-gin

我尝试使用 Gin 框架验证枚举在 Golang 中是否有效。

我遇到了这个解决方案:

但这种方法的缺点是每次枚举值发生变化时我们都必须手动更改硬编码值。

有没有什么方法可以通过名称作为字符串获取枚举,而无需创建映射并将其注册到类型中?

期望的结果:

package main

import "github.com/go-playground/validator"

type Status int

const (
    Single Status = iota
    Married
    Other
)

type User struct {
    Status Status `json:"status" binding:"Enum=Status"`
}

func Enum(fl validator.FieldLevel) bool {
    enumType := fl.Param() // Status
    // get `Status` by `enumType` and validate it...
    return true
}

func main() {}

最佳答案

此解决方案的方法之一可能是:

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
    "github.com/gin-gonic/gin/binding"
    "github.com/go-playground/validator/v10"
)

type Enum interface {
    IsValid() bool
}

type Status int

const (
    Single Status = iota + 1 // add + 1 otherwise validation won't work for 0
    Married
    Other
)

func (s Status) IsValid() bool {
    switch s {
    case Single, Married, Other:
        return true
    }

    return false
}

type Input struct {
    RelationshipStatus Status `json:"relationship_status" binding:"required,enum"`
}

func UpdateRelationshipStatus(context *gin.Context) {
    input := Input{}

    err := context.ShouldBindJSON(&input)
    if err != nil {
        context.JSON(http.StatusBadRequest, gin.H{"message": "enum is not valid"})
        return
    }

    context.JSON(http.StatusOK, gin.H{"message": "correct enum"})
}

func ValidateEnum(fl validator.FieldLevel) bool {
    value := fl.Field().Interface().(Enum)
    return value.IsValid()
}

func main() {
    if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
        v.RegisterValidation("enum", ValidateEnum)
    }

    router := gin.Default()

    router.POST("", UpdateRelationshipStatus)

    router.Run(":3000")
}

输出:

curl \
  --request POST \
  --data '{"relationship_status": 0}' \
  http://localhost:3000/
# {"message":"enum is not valid"}

curl \
  --request POST \
  --data '{"relationship_status": 1}' \
  http://localhost:3000/
# {"message":"correct enum"}

curl \
  --request POST \
  --data '{"relationship_status": 2}' \
  http://localhost:3000/
# {"message":"correct enum"}

curl \
  --request POST \
  --data '{"relationship_status": 3}' \
  http://localhost:3000/
# {"message":"correct enum"}

curl \
  --request POST \
  --data '{"relationship_status": 4}' \
  http://localhost:3000/
# {"message":"enum is not valid"}

关于go - 使用 Gin 框架验证 Golang 中的枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71278746/

相关文章:

winapi - 在 Go for Windows 中获取窗口几何

go - 当前函数的名称

interface - GO 使用接口(interface)作为字段

sdl - 如何在 Windows 上构建 Go-SDL?

将字符串作为 %09d 的参数时,sprintf 的 golang 错误

go - 如何为 golang gin 框架返回 gzip 响应

web-services - Gin 通配符路由与现有子项冲突

html - 如何在 golang gin web 框架中使用 golang 数据呈现 HTML?

go - 在本地主机 :8080 getting CORS from frontend running on 9090 上运行的服务器

go - 运行前如何通过gin合并多个路由器