Skip to content

Instantly share code, notes, and snippets.

@rugwirobaker
Last active Oct 1, 2018
Embed
What would you like to do?
func (api ProductsAPI) Create() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var product models.Product
if r.Method != http.MethodPost {
code := http.StatusMethodNotAllowed
httpError := common.NewError(common.HTTPFriendlyStatus(code), code)
common.SendErrorResult(w, httpError)
return
}
if err := json.NewDecoder(r.Body).Decode(&product); err != nil {
code := http.StatusBadRequest
httpError := common.NewError(common.HTTPFriendlyStatus(code), code)
common.SendErrorResult(w, httpError)
return
}
data := fmt.Sprintf("%s: Created!\n", api.Text)
common.SendSuccessResult(w, data)
}
}
.....
//SendErrorResult ...
func SendErrorResult(res http.ResponseWriter, err error) {
res.Header().Set("content-type", "application/json")
encoder := json.NewEncoder(res)
encoder.SetEscapeHTML(false)
obj, ok := err.(interface{ Status() int })
if ok == true {
res.WriteHeader(obj.Status())
}
m := func(r string) string {
if r == "" {
return r
}
return strings.ToUpper(string(r[0])) + string(r[1:])
}(err.Error())
encoder.Encode(APIErrorMessage{"error", m})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment