0
0
Fork 0

add a basic group mechanism

This adds a basic group mechanism to run a bunch of middlewares for the
same path.
This commit is contained in:
Gibheer 2014-08-01 22:41:17 +02:00
parent 53732c24e5
commit 019ca58e63
2 changed files with 27 additions and 8 deletions

View File

@ -16,6 +16,8 @@ type Router struct {
funcList []ContextFunc
// the router to use as the main entity
router *httprouter.Router
// the parent router, if any
parent *Router
}
// Bundle all parameters into the context to make it easier to push important
@ -38,7 +40,14 @@ type Context struct {
type ContextFunc func(*Context) error
func NewRouter() *Router {
return &Router{"", make([]ContextFunc, 0), httprouter.New()}
return &Router{"", make([]ContextFunc, 0), httprouter.New(), nil}
}
func (r *Router) fullpath(path string) string {
if r.parent != nil {
return r.parent.fullpath(r.path + path)
}
return r.path + path
}
func (r *Router) Get(path string, target ContextFunc) {
@ -57,14 +66,10 @@ func (r *Router) Delete(path string, target ContextFunc) {
r.addRoute("DELETE", path, target)
}
func (r *Router) Use(middleware ContextFunc) {
r.funcList = addToFuncList(r.funcList, middleware)
}
func (router *Router) addRoute(method, path string, target ContextFunc) {
router.router.Handle(
method,
router.path + path,
router.fullpath(path),
router.createHandleFunction(target),
)
}
@ -84,6 +89,14 @@ func (r *Router) createHandleFunction(target ContextFunc) httprouter.Handle {
}
}
func (r *Router) Use(middleware ContextFunc) {
r.funcList = addToFuncList(r.funcList, middleware)
}
func (r *Router) NewGroup(path string) *Router {
return &Router{path, make([]ContextFunc, 0), r.router, r}
}
func (r *Router) Start() {
log.Print("Starting to listen for incoming requests ...")
log.Fatal(http.ListenAndServe(":9292", r.router))

10
main.go
View File

@ -8,8 +8,14 @@ import (
func main() {
router := lib.NewRouter()
router.Use(func(c *lib.Context) error {
fmt.Fprint(c.Response, "Hello says the middleware!")
authentication := router.NewGroup("/admin")
authentication.Use(func(c *lib.Context) error {
c.Response.Header().Add("Content-Type", "text/html")
fmt.Fprint(c.Response, "Hello says the middleware!<br />")
return nil
})
authentication.Get("/", func(c *lib.Context) error {
fmt.Fprint(c.Response, "Admin panel, yay!")
return nil
})
controller.DefineRoutes(router)