chore: started working on the api
This commit is contained in:
@@ -14,6 +14,7 @@ import (
|
||||
|
||||
dbtypes "git.andr3h3nriqu3s.com/andr3/fyp/logic/db_types"
|
||||
"github.com/charmbracelet/log"
|
||||
"github.com/goccy/go-json"
|
||||
)
|
||||
|
||||
func Mul(n1 int, n2 int) int {
|
||||
@@ -347,6 +348,43 @@ type Context struct {
|
||||
Db *sql.DB
|
||||
}
|
||||
|
||||
func (c Context) ToJSON(r *http.Request, dat any) *Error {
|
||||
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
|
||||
err := decoder.Decode(dat)
|
||||
if err != nil {
|
||||
return c.Error500(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c Context) SendJSON(w http.ResponseWriter, dat any) *Error {
|
||||
w.Header().Add("content-type", "application/json")
|
||||
text, err := json.Marshal(dat)
|
||||
if err != nil {
|
||||
return c.Error500(err)
|
||||
}
|
||||
if _, err = w.Write(text); err != nil {
|
||||
return c.Error500(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c Context) SendJSONStatus(w http.ResponseWriter, status int, dat any) *Error {
|
||||
w.Header().Add("content-type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
text, err := json.Marshal(dat)
|
||||
if err != nil {
|
||||
return c.Error500(err)
|
||||
}
|
||||
if _, err = w.Write(text); err != nil {
|
||||
return c.Error500(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c Context) Error400(err error, message string, w http.ResponseWriter, path string, base string, data AnyMap) *Error {
|
||||
c.SetReportCaller(true)
|
||||
c.Logger.Error(message)
|
||||
@@ -609,6 +647,10 @@ func NewHandler(db *sql.DB) *Handle {
|
||||
if r.Header.Get("Request-Type") == "htmlfull" {
|
||||
ans = HTMLFULL
|
||||
}
|
||||
if r.Header.Get("content-type") == "application/json" {
|
||||
ans = JSON
|
||||
}
|
||||
|
||||
//TODO JSON
|
||||
|
||||
//Login state
|
||||
@@ -618,6 +660,9 @@ func NewHandler(db *sql.DB) *Handle {
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Add("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Add("Access-Control-Allow-Headers", "*")
|
||||
|
||||
if r.Method == "GET" {
|
||||
x.handleGets(w, r, context)
|
||||
return
|
||||
@@ -630,6 +675,9 @@ func NewHandler(db *sql.DB) *Handle {
|
||||
x.handleDeletes(w, r, context)
|
||||
return
|
||||
}
|
||||
if r.Method == "OPTIONS" {
|
||||
return
|
||||
}
|
||||
panic("TODO handle method: " + r.Method)
|
||||
})
|
||||
|
||||
|
||||
Reference in New Issue
Block a user