在 go-gin 中验证 body 的更优雅的方式

More elegant way of validate body in go-gin

是否有更优雅的方法来使用 go-gin 验证 json bodyroute id

package controllers

import (
    "giin/inputs"
    "net/http"

    "github.com/gin-gonic/gin"
    "github.com/google/uuid"
)

func GetAccount(context *gin.Context) {

    // validate if `accountId` is valid `uuid``
    _, err := uuid.Parse(context.Param("accountId"))
    if err != nil {
        context.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
        return
    }

    // some logic here...

    context.JSON(http.StatusOK, gin.H{"message": "account received"})
}

func AddAccount(context *gin.Context) {

    // validate if `body` is valid `inputs.Account`
    var input inputs.Account
    if error := context.ShouldBindJSON(&input); error != nil {
        context.JSON(http.StatusBadRequest, error.Error())
        return
    }

    // some logic here...

    context.JSON(http.StatusOK, gin.H{"message": "account added"})
}

我创建了中间件,它能够检测 accountId 是否通过,如果是,则验证它,如果 accountId 不是 uuid 格式,则 return 错误请求,但我不能对 body 做同样的事情,因为 AccountBodyMiddleware 试图验证每个请求,有人可以帮助我吗?

而且,如果我可以验证任何类型的 body 而不是为每个 json body

创建新的中间件,那就太好了
package main

import (
    "giin/controllers"
    "giin/inputs"
    "net/http"

    "github.com/gin-gonic/gin"
    "github.com/google/uuid"
)

func AccountIdMiddleware(c *gin.Context) {
    id := c.Param("accountId")
    if id == "" {
        c.Next()
        return
    }
    if _, err := uuid.Parse(id); err != nil {
        c.JSON(http.StatusBadRequest, "uuid not valid")
        c.Abort()
        return
    }
}

func AccountBodyMiddleware(c *gin.Context) {
    var input inputs.Account
    if error := c.ShouldBindJSON(&input); error != nil {
        c.JSON(http.StatusBadRequest, "body is not valid")
        c.Abort()
        return
    }
    c.Next()
}

func main() {
    r := gin.Default()
    r.Use(AccountIdMiddleware)
    r.Use(AccountBodyMiddleware)

    r.GET("/account/:accountId", controllers.GetAccount)
    r.POST("/account", controllers.AddAccount)
    r.Run(":5000")
}

使用中间件肯定不是解决问题的方法,您的直觉是正确的!以 FastAPI 为灵感,我通常为我拥有的每个 request/response 创建模型。然后,您可以将这些模型绑定为查询、路径或主体模型。查询模型绑定的示例(只是为了向您展示您不仅可以将其用于 json post 请求):

type User struct {
    UserId            string                     `form:"user_id"`
    Name              string                     `form:"name"`
}

func (user *User) Validate() errors.RestError {
    if _, err := uuid.Parse(id); err != nil {
        return errors.BadRequestError("user_id not a valid uuid")
    }
    return nil
}

其中errors只是一个你可以在本地定义的包,这样就可以return直接通过以下方式验证错误:

func GetUser(c *gin.Context) {

    // Bind query model
    var q User
    if err := c.ShouldBindQuery(&q); err != nil {
        restError := errors.BadRequestError(err.Error())
        c.JSON(restError.Status, restError)
        return
    }

    // Validate request
    if err := q.Validate(); err != nil {
        c.JSON(err.Status, err)
        return
    }

    // Business logic goes here
}

奖励:通过这种方式,您还可以从高级别组合结构并调用内部验证函数。我认为这就是你试图通过使用中间件(组合验证)来完成的:

type UserId struct {
    Id string
}

func (userid *UserId) Validate() errors.RestError {
    if _, err := uuid.Parse(id); err != nil {
        return errors.BadRequestError("user_id not a valid uuid")
    }
    return nil
}

type User struct {
    UserId
    Name string 
}

func (user *User) Validate() errors.RestError {
    if err := user.UserId.Validate(); err != nil {
        return err
    }

    // Do some other validation
    
    return nil
}

额外奖励:如果您有兴趣,请在此处阅读有关后端路由设计和 model-based 验证的更多信息 Softgrade - In Depth Guide to Backend Route Design

作为参考,这里有一个错误结构示例:

type RestError struct {
    Message string `json:"message"`
    Status  int    `json:"status"`
    Error   string `json:"error"`
}

func BadRequestError(message string) *RestError {
    return &RestError{
        Message: message,
        Status:  http.StatusBadRequest,
        Error:   "Invalid Request",
    }
}