Files
latosa-escrima/backend/router.go
gom-by 57fb532965 --help
Signed-off-by: gom-by <gom-by@users.noreply.github.com>
2025-01-15 15:25:43 +01:00

90 lines
1.9 KiB
Go

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 {
Handler HandlerFunc
Middleware func(http.Handler) http.Handler
}
func HandleRoutes(mux *http.ServeMux, routes map[string]Handler) {
for pattern, handler := range routes {
if handler.Middleware == nil {
mux.HandleFunc(pattern, handler.Handler)
} else {
HandleMiddlewareRoute(
pattern,
handler.Handler,
handler.Middleware,
mux,
)
}
}
}