Skip to content
This repository has been archived by the owner on Apr 7, 2023. It is now read-only.

Commit

Permalink
🚧 Added error handlers and status codes for unsuccessful requests.
Browse files Browse the repository at this point in the history
  • Loading branch information
RiccardoBiosas committed Jul 4, 2020
1 parent fde1845 commit 28247d2
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
10 changes: 6 additions & 4 deletions api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ func (a *Api) register(w http.ResponseWriter, r *http.Request) {

err = user.CreateUser(a.DB)
if err != nil {
log.Fatal(err)
helpers.RespondWithError(w, http.StatusConflict, "Public key already registered!")
return
}
resp := map[string]string{"account": user.PublicKey}
helpers.RespondWithJSON(w, 201, resp)
Expand All @@ -74,8 +75,10 @@ func (a *Api) getNonce(w http.ResponseWriter, r *http.Request) {
PublicKey: pb,
}
user.GetUserNonce(a.DB)
// resp, _ := json.Marshal(user.Nonce)
// w.Write(resp)
if user.Nonce == "" {
helpers.RespondWithError(w, http.StatusNotFound, "No matching public key was found!")
return
}
resp := map[string]string{"nonce": user.Nonce}
helpers.RespondWithJSON(w, 200, resp)
}
Expand Down Expand Up @@ -116,5 +119,4 @@ func (a *Api) sendSignature(w http.ResponseWriter, r *http.Request) {
}
resp := map[string]bool{"authenticated": isClientAddressEqualToRecoveredAddress}
helpers.RespondWithJSON(w, 201, resp)
// json.NewEncoder(w).Encode(isClientAddressEqualToRecoveredAddress)
}
5 changes: 4 additions & 1 deletion helpers/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@ func EnablePostRequestsCors(w *http.ResponseWriter) {

func RespondWithJSON(w http.ResponseWriter, statusCode int, payload interface{}) {
resp, _ := json.Marshal(payload)

w.WriteHeader(statusCode)
w.Write(resp)
}

func RespondWithError(w http.ResponseWriter, statusCode int, errorMsg string) {
RespondWithJSON(w, statusCode, map[string]string{"error": errorMsg})
}

0 comments on commit 28247d2

Please sign in to comment.