Router a good
This commit is contained in:
46
router.go
Normal file
46
router.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type Router struct {
|
||||
t *tree
|
||||
}
|
||||
|
||||
func New() *Router {
|
||||
return &Router{
|
||||
t: newTree(),
|
||||
}
|
||||
}
|
||||
|
||||
func (rt *Router) Add(path string, foo http.HandlerFunc) error {
|
||||
return rt.t.Insert(path, foo)
|
||||
}
|
||||
|
||||
func (rt *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
foo := rt.t.Lookup(r.URL.Path)
|
||||
if foo == nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
foo(w, r)
|
||||
}
|
||||
|
||||
func Params(r *http.Request, toSet ...*string) error {
|
||||
params := r.Header[WildcardHeader]
|
||||
if len(params) != len(toSet) {
|
||||
return errors.New("missing params")
|
||||
}
|
||||
for i := range params {
|
||||
if len(params[i]) < 1 {
|
||||
return errors.New("empty params")
|
||||
}
|
||||
if toSet[i] == nil {
|
||||
return errors.New("cannot set nil param")
|
||||
}
|
||||
*toSet[i] = params[i]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user