Skip to content

Instantly share code, notes, and snippets.

@diegoholiveira
Last active April 28, 2020 22:00
Show Gist options
  • Save diegoholiveira/49cce0e1d5fd8c441e675955423ae3e1 to your computer and use it in GitHub Desktop.
Save diegoholiveira/49cce0e1d5fd8c441e675955423ae3e1 to your computer and use it in GitHub Desktop.
type (
PurchasePersister interface {
Persist(context.Context, purchases.Purchase) error
}
PurchaseHandler struct {
persister PurchasePersister
}
)
func NewPurchaseHandler(persister PurchasePersister) PurchaseHandler {
return PurchaseHandler{
persister: persister,
}
}
func (h PurchaseHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var err error
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
var purchase purchases.Purchase
err = dec.Decode(&purchase)
if err != nil {
render.JSON(w, http.StatusBadRequest, map[string]string{
"error": "Error while decoding the JSON payload",
})
return
}
if dec.More() {
render.JSON(w, http.StatusBadRequest, map[string]string{
"error": "Request body must only contain a single JSON object",
})
return
}
err = h.persister.Persist(r.Context(), purchase)
if err != nil {
render.JSON(w, http.StatusInternalServerError, map[string]string{
"error": err.Error(),
})
}
w.WriteHeader(http.StatusCreated)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment