Skip to content

Instantly share code, notes, and snippets.

@JSila
Last active July 4, 2017 09:27
Show Gist options
  • Save JSila/1896472372004b1b8b0eabf48981ecd5 to your computer and use it in GitHub Desktop.
Save JSila/1896472372004b1b8b0eabf48981ecd5 to your computer and use it in GitHub Desktop.
JSON schema middleware and valide helpers for Go
import (
"context"
"net/http"
"github.com/Sirupsen/logrus"
"github.com/matryer/respond"
)
func CheckJSON(log *logrus.Logger, h http.Handler, data interface{}, contextKey string) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
valid, err := ReadAndValidate(r, NotificationJSONSchema, data)
if err != nil {
log.Panicf("can't read and validate data against schema: %v", err)
respond.WithStatus(w, r, http.StatusInternalServerError)
return
}
if !valid {
respond.WithStatus(w, r, http.StatusBadRequest)
return
}
ctx := context.WithValue(r.Context(), contextKey, data)
h.ServeHTTP(w, r.WithContext(ctx))
})
}
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/xeipuuv/gojsonschema"
)
func ReadAndValidate(r *http.Request, schema string, n interface{}) (bool, error) {
b, err := ioutil.ReadAll(r.Body)
if err != nil {
return false, err
}
defer r.Body.Close()
documentLoader := gojsonschema.NewBytesLoader(b)
schemaLoader := gojsonschema.NewStringLoader(schema)
result, err := gojsonschema.Validate(schemaLoader, documentLoader)
if err != nil {
return false, fmt.Errorf("can't create validator: %v", err)
}
if !result.Valid() {
return false, nil
}
if err := json.NewDecoder(bytes.NewReader(b)).Decode(&n); err != nil {
return false, fmt.Errorf("can't decode json: %v", err)
}
return true, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment