go-validator
path: full-stack/go-chi-server/go-validator.md
- **Created on**: 2024-09-16 15:07:11
installation go validator
go get github.com/go-playground/validator/v10
now the end point for the route is like this Example:
// import packages
type User struct {
Username string `json:"username" validate:"required,min=5,max=20"`
Email string `json:"email" validate:"required,email"`
Age int `json:"age" validate:"gte=18,lte=120"`
}
func main() {
r = chi.Router() // creating a router
r.Get("/weclome", sayWelcome) // adding an end point
return
}
func sayWelcome(w http.ResponseWriter, r *http.Request) {
newUser = User {
Username: "yosef", Email: "yooo@mgailgmail.com", age: 20,
} // creating a instance from the struct user
err := valiate.New(newUser) // starting validation the struct
if err != nil { // if there an error
// Validation failed, handle the error
errors := err.(validator.ValidationErrors)
http.Error(w, fmt.Sprintf("Validation error: %s", errors), http.StatusBadRequest)
return
}
// Send a success response
w.WriteHeader(http.StatusOK) // if the struct is valid
fmt.Fprintf(w, "User created successfully!")
}
continue:go-mongodb.md
before:go-chi.md