@@ -3,8 +3,69 @@ package main
|
||||
import (
|
||||
"net/http"
|
||||
api "fr.latosa-escrima/api"
|
||||
"encoding/json"
|
||||
core "fr.latosa-escrima/api/core"
|
||||
)
|
||||
|
||||
type JSONStatus string
|
||||
|
||||
const (
|
||||
Error JSONStatus = "Error"
|
||||
Success JSONStatus = "Success"
|
||||
)
|
||||
|
||||
type JSONResponse interface {
|
||||
ToJSON() ([]byte, error)
|
||||
Respond(w http.ResponseWriter, code int)
|
||||
}
|
||||
|
||||
type JSONError struct {
|
||||
Status JSONStatus `json:"status"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
type JSONSuccess struct {
|
||||
Status JSONStatus `json:"status"`
|
||||
Message string `json:"message"`
|
||||
Data any `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
func (r *JSONError) ToJSON() ([]byte, error) {
|
||||
return json.Marshal(r)
|
||||
}
|
||||
|
||||
func (r *JSONSuccess) ToJSON() ([]byte, error) {
|
||||
return json.Marshal(r)
|
||||
}
|
||||
|
||||
func defaultResponse(r JSONResponse, w http.ResponseWriter, code int) {
|
||||
jsonData, err := r.ToJSON()
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusNotAcceptable)
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(code)
|
||||
w.Write(jsonData)
|
||||
}
|
||||
|
||||
func (r JSONError) Respond(w http.ResponseWriter, code int) {
|
||||
defaultResponse(&r, w, code)
|
||||
}
|
||||
|
||||
func (r JSONSuccess) Respond(w http.ResponseWriter, code int) {
|
||||
defaultResponse(&r, w, code)
|
||||
}
|
||||
|
||||
func HandleMiddlewareRoute(pattern string,
|
||||
handler func(w http.ResponseWriter, r *http.Request),
|
||||
middleware func(http.Handler) http.Handler,
|
||||
mux *http.ServeMux,
|
||||
) {
|
||||
// mux.HandleFunc(pattern, handler)
|
||||
mux.Handle(pattern, middleware(http.HandlerFunc(handler)))
|
||||
}
|
||||
|
||||
type HandlerFunc func(w http.ResponseWriter, r *http.Request)
|
||||
|
||||
type Handler struct {
|
||||
@@ -17,7 +78,7 @@ func HandleRoutes(mux *http.ServeMux, routes map[string]Handler) {
|
||||
if handler.Middleware == nil {
|
||||
mux.HandleFunc(pattern, handler.Handler)
|
||||
} else {
|
||||
api.HandleMiddlewareRoute(
|
||||
HandleMiddlewareRoute(
|
||||
pattern,
|
||||
handler.Handler,
|
||||
handler.Middleware,
|
||||
|
||||
Reference in New Issue
Block a user