我如何在golang中验证rest api请求的主体结构

ube*_*ebu 3 go go-fiber

例如,我试图确保发布请求的正文包含正文的准确结构,如果不是,则应抛出错误

例如我有以下功能

func UpdatePassword(c *fiber.Ctx) error {

    type UpdatePasswordData struct {
        Password  string `json:"password" form:"password"`
        NewPassword string `json:"new_password" form:"new_password"`
        NewPasswordConfirm string `json:"new_password_confirm" form:"new_password_confirm"`
    }
    
    data := UpdatePasswordData{}

    if err := c.BodyParser(&data); err != nil {
        return err
    }

    var user models.User
    
    if data.NewPassword != data.NewPasswordConfirm {
        c.Status(400)
        return c.JSON(fiber.Map{
            "message": "passwords do not match",
        })
    }

    email, _ := middlewares.GetUserEmail(c)

    newPassword := models.HashPassword(data.NewPassword)

    database.DB.Model(&user).Select("Password").Where("email = ?", email).Updates(map[string]interface{}{"Password": newPassword})

    return c.JSON(user)
}
Run Code Online (Sandbox Code Playgroud)

POST 请求应该寻找具有此结构的正文

{
    "password": "oldpassword",
    "new_password": "newpassword",
    "new_password_confirm": "newpassword",
}
Run Code Online (Sandbox Code Playgroud)

but currently this endpoint accepts body that does not have this exact structure. So how do i enforce the structure in the body of request, so that if structure does not match, i throw an error?

小智 5

不喜欢杜松子酒,纤维没有内置验证包

使用 go-playground/验证器

go get github.com/go-playground/validator
Run Code Online (Sandbox Code Playgroud)

例子

type UpdatePasswordData struct {
        Password  string `json:"password" validate:"required,min=8,max=32"`
        NewPassword string `json:"new_password" validate:"required,min=8,max=32"`
        NewPasswordConfirm string `json:"new_password_confirm" validate:"eqfield=NewPassword"`
}

func UpdatePassword(c *fiber.Ctx) error {
  var body UpdatePasswordData
  if err := c.BodyParser(&body); err != nil {
    return err
  }

  validate := validator.New()
  if err := validate.Struct(body); err != nil {
    return err
  }

  // do others
  // get current user, check password == hash(body.password)
  // save new passworld
}
Run Code Online (Sandbox Code Playgroud)

或者您可以查看 Fiber Office 文档https://docs.go Fiber.io/guide/validation#validator-package