How to Implement Request Validation in Go

Web
Implement request validation in Go by using the validator library to define struct tags and run validation checks.

Use the github.com/go-playground/validator library to define validation rules on struct fields and run them via validator.Validate.

package main

import (
	"fmt"
	"github.com/go-playground/validator/v10"
)

type User struct {
	Name  string `validate:"required,min=3,max=50"`
	Email string `validate:"required,email"`
	Age   int    `validate:"gte=18,lte=120"`
}

func main() {
	validate := validator.New()
	user := User{Name: "A", Email: "invalid", Age: 15}

	if err := validate.Struct(user); err != nil {
		fmt.Println("Validation failed:", err)
		return
	}
	fmt.Println("Validation passed")
}

Install the library with go get github.com/go-playground/validator/v10.