2024-05-19 20:48:06 +03:00
|
|
|
package ss
|
2024-01-10 20:11:02 +03:00
|
|
|
|
|
|
|
import (
|
|
|
|
"strings"
|
|
|
|
//"fmt"
|
|
|
|
//"path"
|
|
|
|
)
|
|
|
|
|
|
|
|
// The type implements path routing for requests.
|
|
|
|
type PathRouter struct {
|
|
|
|
pathMap map[string] Handler
|
2024-02-25 20:20:41 +03:00
|
|
|
def Handler
|
2024-01-10 20:11:02 +03:00
|
|
|
}
|
|
|
|
|
2024-05-19 20:48:06 +03:00
|
|
|
// Returns new empty PathRouter with the def
|
|
|
|
// specified as the default fallback.
|
|
|
|
func Path(def Handler) *PathRouter {
|
2024-01-10 20:11:02 +03:00
|
|
|
ret := &PathRouter{}
|
|
|
|
ret.pathMap = map[string] Handler{}
|
2024-05-19 20:48:06 +03:00
|
|
|
ret.def = def
|
2024-01-10 20:11:02 +03:00
|
|
|
return ret
|
|
|
|
}
|
|
|
|
|
|
|
|
// Define new handler for the specified path.
|
|
|
|
// The defined path must not contain slashes and will panic otherwise.
|
2024-02-25 20:20:41 +03:00
|
|
|
func (router *PathRouter) Case(pth string, handler Handler) *PathRouter {
|
2024-01-10 20:11:02 +03:00
|
|
|
_, 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 {
|
2024-02-25 20:20:41 +03:00
|
|
|
if router.def == nil {
|
|
|
|
c.NotFound()
|
|
|
|
} else {
|
|
|
|
router.def.Handle(c)
|
|
|
|
}
|
2024-01-10 20:11:02 +03:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-01-10 21:19:23 +03:00
|
|
|
c.RelUrl.Path = rest
|
2024-01-10 20:11:02 +03:00
|
|
|
handler.Handle(c)
|
|
|
|
}
|
|
|
|
|
2024-02-25 20:20:41 +03:00
|
|
|
|