88 lines
1.8 KiB
Go
88 lines
1.8 KiB
Go
package main
|
|
|
|
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)
|
|
}
|
|
|
|
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,
|
|
)
|
|
}
|
|
}
|
|
}
|