Files
latosa-escrima/backend/api/core/router.go
2025-01-16 14:12:32 +01:00

78 lines
1.6 KiB
Go

package core
import (
"encoding/json"
"net/http"
)
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)
}
type Middleware func(http.Handler) http.Handler
type Handler struct {
Handler http.HandlerFunc
Middlewares []Middleware
}
func HandleRoutes(mux *http.ServeMux, routes map[string]Handler) {
for pattern, handler := range routes {
if handler.Middlewares == nil {
mux.HandleFunc(pattern, handler.Handler)
} else {
h := http.HandlerFunc(handler.Handler)
for _, middleware := range handler.Middlewares {
h = http.HandlerFunc(middleware(h).ServeHTTP)
}
mux.Handle(pattern, h)
}
}
}