Last active
July 4, 2017 09:27
-
-
Save JSila/1896472372004b1b8b0eabf48981ecd5 to your computer and use it in GitHub Desktop.
JSON schema middleware and valide helpers for Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
}) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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