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)
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?