84 lines
1.9 KiB
Go
84 lines
1.9 KiB
Go
package router
|
|
|
|
type Router struct {
|
|
get Tree
|
|
post Tree
|
|
delete Tree
|
|
put Tree
|
|
patch Tree
|
|
head Tree
|
|
connect Tree
|
|
trace Tree
|
|
options Tree
|
|
}
|
|
|
|
// Create a new Router containing trees for every HTTP method.
|
|
func New() *Router {
|
|
return &Router{}
|
|
}
|
|
|
|
// Registers a new handler for the given method and path.
|
|
func (router *Router) Add(method string, path string, handler string) {
|
|
tree := router.selectTree(method)
|
|
tree.Add(path, handler)
|
|
}
|
|
|
|
// Finds the handler and parameters for the given route.
|
|
func (router *Router) Lookup(method string, path string) (string, []Parameter) {
|
|
if method[0] == 'G' {
|
|
return router.get.Lookup(path)
|
|
}
|
|
|
|
tree := router.selectTree(method)
|
|
return tree.Lookup(path)
|
|
}
|
|
|
|
// Finds the handler and parameters for the given route without using any memory allocations.
|
|
func (router *Router) LookupNoAlloc(method string, path string, addParameter func(string, string)) string {
|
|
if method[0] == 'G' {
|
|
return router.get.LookupNoAlloc(path, addParameter)
|
|
}
|
|
|
|
tree := router.selectTree(method)
|
|
return tree.LookupNoAlloc(path, addParameter)
|
|
}
|
|
|
|
// Traverses all trees and calls the given function on every node.
|
|
func (router *Router) Map(transform func(string) string) {
|
|
router.get.Map(transform)
|
|
router.post.Map(transform)
|
|
router.delete.Map(transform)
|
|
router.put.Map(transform)
|
|
router.patch.Map(transform)
|
|
router.head.Map(transform)
|
|
router.connect.Map(transform)
|
|
router.trace.Map(transform)
|
|
router.options.Map(transform)
|
|
}
|
|
|
|
// Returns the tree of the given HTTP method.
|
|
func (router *Router) selectTree(method string) *Tree {
|
|
switch method {
|
|
case "GET":
|
|
return &router.get
|
|
case "POST":
|
|
return &router.post
|
|
case "DELETE":
|
|
return &router.delete
|
|
case "PUT":
|
|
return &router.put
|
|
case "PATCH":
|
|
return &router.patch
|
|
case "HEAD":
|
|
return &router.head
|
|
case "CONNECT":
|
|
return &router.connect
|
|
case "TRACE":
|
|
return &router.trace
|
|
case "OPTIONS":
|
|
return &router.options
|
|
default:
|
|
return nil
|
|
}
|
|
}
|