Instantly share code, notes, and snippets.

Embed
What would you like to do?
Check JSON middleware
package main
import (
"time"
"net/http"
"log"
"io/ioutil"
"encoding/json"
router "github.com/go-chi/chi"
routermw "github.com/go-chi/chi/middleware"
"bytes"
)
func withJsonCheck(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r == nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("nil??"))
return // Doesn't serve next
}
// TODO also check req headers content-type
raw, err := ioutil.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("error reader"))
return // Doesn't serve next
}
s := string(raw)
if s == "" {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("not valid JSON (empty) :("))
return // Doesn't serve next
}
if s == "{}" {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("not valid JSON (empty obj) :("))
return // Doesn't serve next
}
var ignore interface{}
err = json.Unmarshal(raw, &ignore)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("not valid JSON (unmarshal) :("))
return // Doesn't serve next
}
r.Body = ioutil.NopCloser(bytes.NewBuffer(raw)) // Must set body for next
h.ServeHTTP(w, r) // Valid json -> serve next MW
})
}
func home(w http.ResponseWriter, r *http.Request) {
raw, err := ioutil.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("error in handler"))
return
}
w.Write([]byte("hey i got valid json!\n"))
w.Write(raw)
}
func main() {
r := router.NewRouter()
r.Use(routermw.Logger)
r.Use(routermw.Recoverer)
// JSON check
r.Use(withJsonCheck)
r.Post(`/`, home)
srv := http.Server{
Addr: `localhost:8080`,
Handler: r,
WriteTimeout: time.Second * 30,
ReadHeaderTimeout: time.Second * 30,
IdleTimeout: time.Second * 30,
ReadTimeout: time.Second * 30,
}
log.Printf("Listening address '%v'\n", srv.Addr)
srv.ListenAndServe()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment