66 lines
1.2 KiB
Go
66 lines
1.2 KiB
Go
|
package bond
|
||
|
|
||
|
import (
|
||
|
"strings"
|
||
|
//"fmt"
|
||
|
//"path"
|
||
|
)
|
||
|
|
||
|
// The type implements path routing for requests.
|
||
|
type PathRouter struct {
|
||
|
pathMap map[string] Handler
|
||
|
}
|
||
|
|
||
|
// Returns new empty PathRouter.
|
||
|
func Path() *PathRouter {
|
||
|
ret := &PathRouter{}
|
||
|
ret.pathMap = map[string] Handler{}
|
||
|
return ret
|
||
|
}
|
||
|
|
||
|
// Define new handler for the specified path.
|
||
|
// The defined path must not contain slashes and will panic otherwise.
|
||
|
func (router *PathRouter) Def(pth string, handler Handler) *PathRouter {
|
||
|
_, dup := router.pathMap[pth]
|
||
|
if dup {
|
||
|
panic(DupDefErr)
|
||
|
}
|
||
|
router.pathMap[pth] = handler
|
||
|
return router
|
||
|
}
|
||
|
|
||
|
// Implementing the Handler.
|
||
|
func (router *PathRouter) Handle(c *Context) {
|
||
|
pth := c.Path()
|
||
|
var splits []string
|
||
|
var name, rest string
|
||
|
|
||
|
if len(pth)>0 && pth[0] == '/' { // Handling the root path.
|
||
|
splits = strings.SplitN(pth, "/", 3)
|
||
|
if len(splits) > 1 {
|
||
|
name = splits[1]
|
||
|
}
|
||
|
if len(splits) > 2 {
|
||
|
rest = splits[2]
|
||
|
}
|
||
|
} else { // Handling the relative path. (second or n-th call)
|
||
|
splits = strings.SplitN(pth, "/", 2)
|
||
|
if len(splits) > 0 {
|
||
|
name = splits[0]
|
||
|
}
|
||
|
if len(splits) > 1 {
|
||
|
rest = splits[1]
|
||
|
}
|
||
|
}
|
||
|
|
||
|
handler, ok := router.pathMap[name]
|
||
|
if !ok {
|
||
|
c.NotFound()
|
||
|
return
|
||
|
}
|
||
|
|
||
|
c.R.URL.Path = rest
|
||
|
handler.Handle(c)
|
||
|
}
|
||
|
|