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