2019-11-15 03:03:56 +00:00
|
|
|
package gophertype
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"git.kirsle.net/apps/gophertype/pkg/controllers"
|
|
|
|
"git.kirsle.net/apps/gophertype/pkg/glue"
|
2019-11-15 04:58:55 +00:00
|
|
|
"git.kirsle.net/apps/gophertype/pkg/middleware"
|
2019-11-15 03:03:56 +00:00
|
|
|
"github.com/gorilla/mux"
|
|
|
|
)
|
|
|
|
|
|
|
|
// SetupRouter sets up the HTTP router.
|
|
|
|
func (s *Site) SetupRouter() error {
|
|
|
|
router := mux.NewRouter()
|
|
|
|
|
2019-11-15 04:58:55 +00:00
|
|
|
router.Use(middleware.CSRF)
|
|
|
|
|
2019-11-15 03:03:56 +00:00
|
|
|
for _, route := range glue.GetControllers() {
|
|
|
|
log.Printf("Register: %+v", route)
|
|
|
|
if len(route.Methods) == 0 {
|
|
|
|
route.Methods = []string{"GET"}
|
|
|
|
}
|
|
|
|
|
|
|
|
route.Methods = append(route.Methods, "HEAD")
|
|
|
|
|
|
|
|
if len(route.Middleware) > 0 {
|
|
|
|
log.Printf("%+v has middlewares!", route)
|
|
|
|
|
|
|
|
handler := route.Middleware[0](http.HandlerFunc(route.Handler))
|
|
|
|
router.Handle(route.Path, handler).Methods(route.Methods...)
|
|
|
|
} else {
|
|
|
|
router.HandleFunc(route.Path, route.Handler).Methods(route.Methods...)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
router.PathPrefix("/").HandlerFunc(controllers.CatchAllHandler)
|
|
|
|
router.NotFoundHandler = http.HandlerFunc(controllers.CatchAllHandler)
|
|
|
|
|
|
|
|
log.Println("Walk the mux.Router:")
|
|
|
|
router.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
|
|
|
|
tpl, err1 := route.GetPathTemplate()
|
|
|
|
met, err2 := route.GetMethods()
|
|
|
|
fmt.Println(tpl, err1, met, err2)
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
|
|
|
|
s.mux = router
|
|
|
|
s.n.UseHandler(router)
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|