Last active
April 28, 2020 22:00
-
-
Save diegoholiveira/49cce0e1d5fd8c441e675955423ae3e1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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