Pakiet walidatora
Walidator Go Fiber jest głównie używany do walidacji parametrów formularza.
Fiber może doskonale wykorzystać pakiet walidatora, aby zapewnić poprawną walidację danych do przechowywania.
Możesz znaleźć szczegółowe opisy walidacji dla pól zawartych w poniższej strukturze:
Przykład walidacji
package main
import (
"fmt"
"log"
"strings"
"github.com/go-playground/validator/v10"
"github.com/gofiber/fiber/v2"
)
type (
User struct {
Name string `validate:"required,min=5,max=20"` // // Mandatory field, minimum length 5 characters, maximum length 20 characters
Age int `validate:"required,teener"` // mandatory field, and the client needs to implement our 'teener' tag format, as we'll see later on
}
ErrorResponse struct {
Error bool
FailedField string
Tag string
Value interface{}
}
XValidator struct {
validator *validator.Validate
}
GlobalErrorHandlerResp struct {
Success bool `json:"success"`
Message string `json:"message"`
}
)
// This is the validator example
// For more information see: https://github.com/go-playground/validator
var validate = validator.New()
func (v XValidator) Validate(data interface{}) []ErrorResponse {
validationErrors := []ErrorResponse{}
errs := validate.Struct(data)
if errs != nil {
for _, err := range errs.(validator.ValidationErrors) {
//In this case, the data object actually holds the User structure
var elem ErrorResponse
elem.FailedField = err.Field() // Export structure field names
elem.Tag = err.Tag() // Exporting structure labels
elem.Value = err.Value() // Exporting field values
elem.Error = true
validationErrors = append(validationErrors, elem)
}
}
return validationErrors
}
func main() {
myValidator := &XValidator{
validator: validate,
}
app := fiber.New(fiber.Config{
// Global custom error handler
ErrorHandler: func(c *fiber.Ctx, err error) error {
return c.Status(fiber.StatusBadRequest).JSON(GlobalErrorHandlerResp{
Success: false,
Message: err.Error(),
})
},
})
// Customize the structure validation label format
myValidator.validator.RegisterValidation("teener", func(fl validator.FieldLevel) bool {
// User.Age needs to match our needs, 12-18 years old.
return fl.Field().Int() >= 12 && fl.Field().Int() <= 18
})
app.Get("/", func(c *fiber.Ctx) error {
// Create an instance of User
var user User
// Bind request data to User struct
if err := c.QueryParser(&user); err != nil {
return err
}
// Validate User struct
validationErrors := myValidator.Validate(user)
if len(validationErrors) > 0 {
errMsgs := make([]string, 0)
for _, err := range validationErrors {
errMsgs = append(errMsgs, fmt.Sprintf(
"[%s]: '%v' | need to be realized '%s'",
err.FailedField,
err.Value,
err.Tag,
))
}
return &fiber.Error{
Code: fiber.ErrBadRequest.Code,
Message: strings.Join(errMsgs, " and "),
}
}
// Logic, validated with success
return c.SendString("Hello, World!")
})
log.Fatal(app.Listen(":3000"))
}
/**
output
[1]
requesting:
GET http://127.0.0.1:3000/
responsive:
{"success":false, "message":"[Name]: '' | need to implement 'required' and [Age]: '0' | need to implement 'required'"}
[2]
requesting:
GET http://127.0.0.1:3000/?name=efdal&age=9
responsive:
{"success":false, "message":"[Age]: '9' | need to implement 'teener'"}
[3]
requesting:
GET http://127.0.0.1:3000/?name=efdal&age=
responsive:
{"success":false,"message":"[Age]: '0' | need to implement 'required'"}
[4]
requesting:
GET http://127.0.0.1:3000/?name=efdal&age=18
responsive:
Hello, World!
**/