Validation
Validation with Fiber
This example demonstrates how to use go-playground/validator for input validation in a Go Fiber application.
Description
This project provides a basic setup for validating request data in a Go Fiber application using the go-playground/validator package. It includes the necessary configuration and code to perform validation on incoming requests.
Requirements
Project Structure
main.go: The main application entry point.config/env.go: Configuration file for environment variables.go.mod: The Go module file..env.example: Example environment variables file. Copy it to.env.
Setup
Clone the repository:
git clone https://github.com/gofiber/recipes.git cd recipes/validationInstall the dependencies:
go mod downloadCopy the example environment file (it sets
PORT=":8080"):cp .env.example .envRun the application:
go run main.go
The application should now be running on http://localhost:8080.
Example Usage
The POST /test endpoint reads a JSON body into a User and validates it. id and firstname are required, and password must be at least 10 characters long.
Send a valid request:
curl -X POST http://localhost:8080/test \ -H "Content-Type: application/json" \ -d '{"id": 1, "firstname": "Ada", "password": "correct-horse"}'The server answers
200with the validated fields. It never echoes the password:{"firstname":"Ada","id":1}Send an invalid request:
curl -X POST http://localhost:8080/test \ -H "Content-Type: application/json" \ -d '{"id": 1, "firstname": "", "password": "short"}'The server answers
400with a message that names each failing field and rule.
Code Overview
main.go
The main Go file sets up the Fiber application, handles HTTP requests, and performs validation using the go-playground/validator package.
config/env.go
The configuration file for loading environment variables.
package config
import "os"
// Config func to get env value
func Config(key string) string {
return os.Getenv(key)
}Conclusion
This example provides a basic setup for validating request data in a Go Fiber application using the go-playground/validator package. It can be extended and customized further to fit the needs of more complex applications.