Browse Source

Added mounting subrouters

master
Gisle Aune 7 years ago
parent
commit
79a24bfe3b
  1. 18
      router.go

18
router.go

@ -9,15 +9,26 @@ import (
"git.aiterp.net/gisle/wrouter/auth"
)
// Route is an interface for a request handler.
type Route interface {
Handle(path string, w http.ResponseWriter, req *http.Request, user *auth.User) bool
}
// Router is the main structure of the wrouter package. It routes requests to the appropriate
// Route
type Router struct {
paths map[Route]string
routes []Route
}
// Mount a router to the router, prefixing all the paths of it
func (router *Router) Mount(path string, subRouter *Router) {
for _, route := range subRouter.routes {
router.Route(strings.Replace(path+subRouter.paths[route], "//", "/", 1), route)
}
}
// Route mounts a route interface to a path
func (router *Router) Route(path string, route Route) {
if router.paths == nil {
router.paths = make(map[Route]string, 16)
@ -27,6 +38,7 @@ func (router *Router) Route(path string, route Route) {
router.routes = append(router.routes, route)
}
// ServeHTTP serves a HTTP request using the router's routes
func (router *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
req.ParseForm()
defer req.Body.Close()
@ -75,18 +87,24 @@ func (router *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
w.Write([]byte("Not Found: " + req.URL.Path))
}
// Resource is a shorthand for creating and adding a new REST resource to the router
func (router *Router) Resource(mount string, list, create ResourceFunc, get, update, delete ResourceIDFunc) {
router.Route(mount, NewResource(list, create, get, update, delete))
}
// Static is a shorthand for creating a static file server on the following path
func (router *Router) Static(mount string, filePath string) {
router.Route(mount, NewStatic(filePath))
}
// Function creates a simple bare-bones handler that just runs a function, prevents
// the need for dummy interfaces
func (router *Router) Function(mount string, function FunctionHandlerFunc) {
router.Route(mount, &functionHandler{function})
}
// Listen creates a http.Server with some sane defaults and pointing to this structure
// for request handling.
func (router *Router) Listen(host string, port int) (*http.Server, error) {
srv := &http.Server{
Addr: fmt.Sprintf("%s:%d", host, port),

Loading…
Cancel
Save