Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do i validate the body structure of rest api request in golang

Tags:

go

go-fiber

I am trying to ensure the body of a post request for example contains exact structure of the body and if not ahould throw an error

for example i have the following function

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)
}

the POST request should be looking for body with this structure

{
    "password": "oldpassword",
    "new_password": "newpassword",
    "new_password_confirm": "newpassword",
}

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?

like image 491
uberrebu Avatar asked Sep 14 '25 19:09

uberrebu


1 Answers

do not like gin, fiber has not builtin validate package

use go-playground/validator

go get github.com/go-playground/validator

example

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
}

or you can see fiber office docs https://docs.gofiber.io/guide/validation#validator-package

like image 187
Goro Avatar answered Sep 17 '25 12:09

Goro