Validating Post Requests
A minimal example of validating post requests in Go
This is a pretty small example of how to validate a post request in Go. It’s not at all difficult, but I’m writing this because I often forget to do this, and I’m hoping that writing it will make me remember.
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/go-playground/validator"
)
const (
string = ":8080"
listenAddr )
//when defining the struct, be sure to indicate validation requirements
//you can also do something like validate:"required,email" to check that the input is an email
type User struct {
string `json:"firstName" validate:"required"`
FirstName string `json:"lastName" validate:"required"`
LastName }
func handleIndex(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
:= "hello, world"
msg
.WriteHeader(http.StatusOK)
w
.Write([]byte(msg))
w
case http.MethodPost:
var u *User
//create a new instance of a validator
:= validator.New()
validate
.NewDecoder(r.Body).Decode(&u)
json
//validate the struct
:= validate.Struct(u)
err
if err != nil {
.Error(w, "invalid request", http.StatusBadRequest)
httpreturn
}
:= "hello, " + u.FirstName + " " + u.LastName
msg
.WriteHeader(http.StatusOK)
w
.Write([]byte(msg))
wdefault:
.Error(w, "method not allowed", http.StatusMethodNotAllowed)
http}
}
func main() {
:= http.NewServeMux()
r
.HandleFunc("/", handleIndex)
r
.Println("Running server")
fmt
:= http.ListenAndServe(listenAddr, r)
err
.Fatal(err)
log}