How do I validate request payloads in Go?

In Go, validating request payloads is an important step in ensuring that your application handles input data correctly and securely. You can utilize various techniques such as struct validation, JSON schema validation, or third-party libraries to validate incoming request payloads.

A common approach is to define a struct that represents the expected payload and then use tags for validation rules. Below is an example using the `validator` package for validation:

package main import ( "encoding/json" "net/http" "github.com/go-playground/validator/v10" ) type User struct { Name string `json:"name" validate:"required"` Email string `json:"email" validate:"required,email"` } var validate *validator.Validate func init() { validate = validator.New() } func validatePayload(w http.ResponseWriter, r *http.Request) { var user User if err := json.NewDecoder(r.Body).Decode(&user); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } if err := validate.Struct(user); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Handle valid payload w.Write([]byte("Payload is valid")) } func main() { http.HandleFunc("/validate", validatePayload) http.ListenAndServe(":8080", nil) }

Keywords: Go request payload validation struct validation JSON validation validator package