diff options
-rw-r--r-- | api/exampleReq.go | 16 | ||||
-rw-r--r-- | api/utils.go | 14 |
2 files changed, 15 insertions, 15 deletions
diff --git a/api/exampleReq.go b/api/exampleReq.go index 40bd55f..54454a1 100644 --- a/api/exampleReq.go +++ b/api/exampleReq.go @@ -1,8 +1,8 @@ package api import ( + "encoding/json" "fmt" - "log" "net/http" redqdb "sinanmohd.com/redq/db" @@ -20,7 +20,6 @@ type RequestApiName struct { type ResponseApiName struct { Bearer *redqdb.Bearer - Error string `json:"error,omitempty"` } func newExamplApiName(db *redqdb.SafeDB) *examplApiName { @@ -36,24 +35,23 @@ func (a *examplApiName) ServeHTTP(rw http.ResponseWriter, r *http.Request) { a.resp.Bearer = &redqdb.Bearer{} err := unmarshal(r.Body, a.req) + fmt.Println(a.req) if err != nil { - log.Println(err) + handleError(err, rw, http.StatusUnprocessableEntity) return } err = a.resp.Bearer.VerifyAndUpdate(a.db, a.req.BearerToken) if err != nil { - log.Println(err) - a.resp.Error = err.Error() + handleError(err, rw, http.StatusUnauthorized) return } - json, err := marshal(a.resp) + json, err := json.Marshal(a.resp) if err != nil { - log.Println(err) - a.resp.Error = err.Error() + handleError(err, rw, http.StatusInternalServerError) return } - fmt.Fprintf(rw, json) + rw.Write(json) } diff --git a/api/utils.go b/api/utils.go index 40b41e6..0fc7d35 100644 --- a/api/utils.go +++ b/api/utils.go @@ -2,7 +2,10 @@ package api import ( "encoding/json" + "fmt" "io" + "log" + "net/http" ) func unmarshal(r io.Reader, v any) error { @@ -19,11 +22,10 @@ func unmarshal(r io.Reader, v any) error { return nil } -func marshal(v any) (string, error) { - b, err := json.Marshal(v) - if err != nil { - return "", err - } +func handleError(err error, rw http.ResponseWriter, status int) { + log.Println(err) - return string(b), nil + rw.WriteHeader(status) + json := fmt.Sprintf(`{"Error": "%v"}`, http.StatusText(status)) + rw.Write([]byte(json)) } |