Validating Post Requests

A minimal example of validating post requests in Go

Published

June 21, 2023

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 (
    listenAddr string = ":8080"
)

//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 {
    FirstName string `json:"firstName" validate:"required"`
    LastName  string `json:"lastName" validate:"required"`
}

func handleIndex(w http.ResponseWriter, r *http.Request) {

    switch r.Method {
    case http.MethodGet:
        msg := "hello, world"

        w.WriteHeader(http.StatusOK)

        w.Write([]byte(msg))

    case http.MethodPost:
        var u *User

        //create a new instance of a validator
        validate := validator.New()

        json.NewDecoder(r.Body).Decode(&u)

        //validate the struct
        err := validate.Struct(u)

        if err != nil {
            http.Error(w, "invalid request", http.StatusBadRequest)
            return
        }

        msg := "hello, " + u.FirstName + " " + u.LastName

        w.WriteHeader(http.StatusOK)

        w.Write([]byte(msg))
    default:
        http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
    }
}

func main() {
    r := http.NewServeMux()

    r.HandleFunc("/", handleIndex)

    fmt.Println("Running server")

    err := http.ListenAndServe(listenAddr, r)

    log.Fatal(err)
}