diff options
author | sinanmohd <sinan@sinanmohd.com> | 2024-03-13 06:47:19 +0530 |
---|---|---|
committer | sinanmohd <sinan@sinanmohd.com> | 2024-03-15 22:20:15 +0530 |
commit | 3dd390c0cb56ffb5a7c1f94afaed0b80ad12cbe1 (patch) | |
tree | d14983bb19b66f3a8c69e8d9ca8dbea296a80df0 /api |
repo: init
Diffstat (limited to 'api')
-rw-r--r-- | api/exampleReq.go | 59 | ||||
-rw-r--r-- | api/main.go | 42 | ||||
-rw-r--r-- | api/utils.go | 29 |
3 files changed, 130 insertions, 0 deletions
diff --git a/api/exampleReq.go b/api/exampleReq.go new file mode 100644 index 0000000..d4ec862 --- /dev/null +++ b/api/exampleReq.go @@ -0,0 +1,59 @@ +package api + +import ( + "fmt" + "log" + "net/http" + + redqdb "sinanmohd.com/redq/db" +) + +type examplApiName struct { + db *redqdb.SafeDB + req *RequestApiName + resp *ResponseApiName +} + +type RequestApiName struct { + BearerToken string +} + +type ResponseApiName struct { + Bearer *redqdb.Bearer + Error string +} + +func newExamplApiName(db *redqdb.SafeDB) *examplApiName { + a := &examplApiName{} + a.db = db + + return a +} + +func (a *examplApiName) ServeHTTP(rw http.ResponseWriter, r *http.Request) { + a.req = &RequestApiName{} + a.resp = &ResponseApiName{} + a.resp.Bearer = &redqdb.Bearer{} + + err := unmarshal(r.Body, a.req) + if err != nil { + log.Println(err) + return + } + + err = a.resp.Bearer.VerifyAndUpdate(a.db, a.req.BearerToken) + if err != nil { + log.Println(err) + a.resp.Error = err.Error() + return + } + + json, err := marshal(a.resp) + if err != nil { + log.Println(err) + a.resp.Error = err.Error() + return + } + + fmt.Fprintf(rw, json) +} diff --git a/api/main.go b/api/main.go new file mode 100644 index 0000000..29f71c9 --- /dev/null +++ b/api/main.go @@ -0,0 +1,42 @@ +package api + +import ( + "fmt" + "net/http" + + redqdb "sinanmohd.com/redq/db" +) + +func Run(db *redqdb.SafeDB) { + const prefix string = "POST /_redq/api" + + exampleApi := newExamplApiName(db) + http.Handle(prefix+"/example", exampleApi) + + http.HandleFunc("GET /{$}", home) + http.ListenAndServe(":8008", nil) +} + +func home(rw http.ResponseWriter, r *http.Request) { + const index string = ` + <!DOCTYPE html> + <html lang="en"> + <head> + <meta charset="UTF-8"> + <title>🚨 redq</title> + </head> + <body> + <center> + <h1 style="font-size: 10em"> + redq is active + </h1> + <p style="font-weight: bold"> + we're soo back 🥳 + </p> + </center> + </body> + </html> + ` + + fmt.Fprint(rw, index) +} diff --git a/api/utils.go b/api/utils.go new file mode 100644 index 0000000..40b41e6 --- /dev/null +++ b/api/utils.go @@ -0,0 +1,29 @@ +package api + +import ( + "encoding/json" + "io" +) + +func unmarshal(r io.Reader, v any) error { + body, err := io.ReadAll(r) + if err != nil { + return err + } + + err = json.Unmarshal(body, v) + if err != nil { + return err + } + + return nil +} + +func marshal(v any) (string, error) { + b, err := json.Marshal(v) + if err != nil { + return "", err + } + + return string(b), nil +} |