Esempio n. 1
0
func DecodeAndValidate(w http.ResponseWriter, r *http.Request, obj interface{}) (err error) {
	decoder := json.NewDecoder(r.Body)
	if err = decoder.Decode(obj); err != nil {
		log.Println("Error in decoding request body. Error is ", err)
		ErrorResponse(w, errors.New("Invalid json details in request body"), http.StatusBadRequest)
		return
	}
	log.Println("decoded object type and value:", fmt.Sprintf("%T", obj), obj)
	valid := validation.Validation{}
	var b bool
	if b, err = valid.RecursiveValid(obj); err != nil || !b {
		var buffer bytes.Buffer
		if valid.HasErrors() {
			for _, validationErr := range valid.Errors {
				buffer.WriteString(validationErr.Field + " " + validationErr.Message + ".")
			}
		}
		err = errors.New(buffer.String())
		ErrorResponse(w, err, http.StatusBadRequest)
	}
	return
}