A FAIRE.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

86 lines
1.9 KiB

/*
------------------------------------------------------------------------------------------------------------------------
####### router ####### Copyright (c) 2021 mls-361 ################################################## MIT License #######
------------------------------------------------------------------------------------------------------------------------
*/
package router
import (
"expvar"
"net/http"
"forge.chapril.org/mls-361/jsonapi"
"github.com/julienschmidt/httprouter"
"forge.chapril.org/armen/armen/internal/components"
)
type router struct {
mux *httprouter.Router
}
func newRouter() *router {
return &router{
mux: httprouter.New(),
}
}
// Build AFAIRE.
func Build(_ *components.Components) components.Router {
cr := newRouter()
cr.mux.PanicHandler = func(rw http.ResponseWriter, _ *http.Request, _ interface{}) {
//AFINIR: logger
rw.WriteHeader(http.StatusInternalServerError)
}
cr.mux.Handle(
http.MethodGet,
"/debug",
func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
expvar.Handler().ServeHTTP(w, r)
},
)
return cr
}
// Handler AFAIRE.
func (cr *router) Handler() http.Handler {
return cr.mux
}
func (cr *router) handle(method string, path string, handler jsonapi.Handler) {
cr.mux.Handle(
method,
path,
func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
var mp map[string]string
if len(ps) > 0 {
mp = make(map[string]string, len(ps))
for _, p := range ps {
mp[p.Key] = p.Value
}
}
handler.Serve(jsonapi.NewRequest(r, w, mp))
},
)
}
// Get AFAIRE.
func (cr *router) Get(path string, handler jsonapi.Handler) {
cr.handle(http.MethodGet, path, handler)
}
// Post AFAIRE.
func (cr *router) Post(path string, handler jsonapi.Handler) {
cr.handle(http.MethodPost, path, handler)
}
/*
######################################################################################################## @(°_°)@ #######
*/