summaryrefslogtreecommitdiff
path: root/api
diff options
context:
space:
mode:
authorsinanmohd <sinan@sinanmohd.com>2024-03-16 09:09:10 +0530
committersinanmohd <sinan@sinanmohd.com>2024-03-16 09:24:06 +0530
commit8fd42493709792ffe85f519c75b085ed65123baa (patch)
tree7da10543c9985b00b0848451487d1dd5d8278650 /api
parentc6ae7acc13d243f7fcd2115be1da142678e71f70 (diff)
api/handleError: init
Diffstat (limited to 'api')
-rw-r--r--api/exampleReq.go16
-rw-r--r--api/utils.go14
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))
}