Skip to content

Instantly share code, notes, and snippets.

@rugwirobaker
Last active October 1, 2018 16:36
Show Gist options
  • Save rugwirobaker/48806cb8c66c57d52b2c7169ae6bf469 to your computer and use it in GitHub Desktop.
Save rugwirobaker/48806cb8c66c57d52b2c7169ae6bf469 to your computer and use it in GitHub Desktop.
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