Adding error codes on bad requests.

This commit is contained in:
sergiotarxz 2021-02-03 19:13:48 +01:00
parent 087b7ceb7b
commit cd235d382d
Signed by: sergiotarxz
GPG Key ID: E5903508B6510AC2

View File

@ -3,11 +3,11 @@ package usercontroller
import (
d "WWWShop/wwwshop/dao/database"
u "WWWShop/wwwshop/dao/usermanager"
"bytes"
"encoding/json"
"fmt"
"net/http"
"strings"
"bytes"
"strings"
)
type UserController struct{}
@ -21,30 +21,35 @@ func (self UserController) POST(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&decoded_user_struct)
if err != nil {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
json_response, _ := EncodeJSONResponse(NewResponseError("Unable to decode json"))
fmt.Fprintf(w, json_response)
return
return
}
if decoded_user_struct.Username == "" {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
json_response, _ := EncodeJSONResponse(NewResponseError("Unable to get username"))
fmt.Fprintf(w, json_response)
return
return
}
if decoded_user_struct.PasswordPlaintext == "" {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
json_response, _ := EncodeJSONResponse(NewResponseError("Unable to get password"))
fmt.Fprintf(w, json_response)
return
return
}
user_manager := u.New(d.DB())
user, err := user_manager.AddWithPlainPassword(decoded_user_struct.Username, decoded_user_struct.PasswordPlaintext)
if err != nil {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
json_response, _ := EncodeJSONResponse(NewResponseError(strings.Join(
[]string{"Unable to create user ", err.Error()},
"")))
fmt.Fprintf(w, json_response)
return
[]string{"Unable to create user ", err.Error()},
"")))
fmt.Fprintf(w, json_response)
return
}
json_response, err := EncodeJSONResponse(user);
json_response, err := EncodeJSONResponse(user)
fmt.Fprintf(w, json_response)
}