123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380 |
- package macaron
- import (
- "net/http"
- "strings"
- "sync"
- )
- var (
-
- _HTTP_METHODS = map[string]bool{
- "GET": true,
- "POST": true,
- "PUT": true,
- "DELETE": true,
- "PATCH": true,
- "OPTIONS": true,
- "HEAD": true,
- }
- )
- type routeMap struct {
- lock sync.RWMutex
- routes map[string]map[string]*Leaf
- }
- func NewRouteMap() *routeMap {
- rm := &routeMap{
- routes: make(map[string]map[string]*Leaf),
- }
- for m := range _HTTP_METHODS {
- rm.routes[m] = make(map[string]*Leaf)
- }
- return rm
- }
- func (rm *routeMap) getLeaf(method, pattern string) *Leaf {
- rm.lock.RLock()
- defer rm.lock.RUnlock()
- return rm.routes[method][pattern]
- }
- func (rm *routeMap) add(method, pattern string, leaf *Leaf) {
- rm.lock.Lock()
- defer rm.lock.Unlock()
- rm.routes[method][pattern] = leaf
- }
- type group struct {
- pattern string
- handlers []Handler
- }
- type Router struct {
- m *Macaron
- autoHead bool
- routers map[string]*Tree
- *routeMap
- namedRoutes map[string]*Leaf
- groups []group
- notFound http.HandlerFunc
- internalServerError func(*Context, error)
-
- handlerWrapper func(Handler) Handler
- }
- func NewRouter() *Router {
- return &Router{
- routers: make(map[string]*Tree),
- routeMap: NewRouteMap(),
- namedRoutes: make(map[string]*Leaf),
- }
- }
- func (r *Router) SetAutoHead(v bool) {
- r.autoHead = v
- }
- type Params map[string]string
- type Handle func(http.ResponseWriter, *http.Request, Params)
- type Route struct {
- router *Router
- leaf *Leaf
- }
- func (r *Route) Name(name string) {
- if len(name) == 0 {
- panic("route name cannot be empty")
- } else if r.router.namedRoutes[name] != nil {
- panic("route with given name already exists: " + name)
- }
- r.router.namedRoutes[name] = r.leaf
- }
- func (r *Router) handle(method, pattern string, handle Handle) *Route {
- method = strings.ToUpper(method)
- var leaf *Leaf
-
- if leaf = r.getLeaf(method, pattern); leaf != nil {
- return &Route{r, leaf}
- }
-
- if !_HTTP_METHODS[method] && method != "*" {
- panic("unknown HTTP method: " + method)
- }
-
- methods := make(map[string]bool)
- if method == "*" {
- for m := range _HTTP_METHODS {
- methods[m] = true
- }
- } else {
- methods[method] = true
- }
-
- for m := range methods {
- if t, ok := r.routers[m]; ok {
- leaf = t.Add(pattern, handle)
- } else {
- t := NewTree()
- leaf = t.Add(pattern, handle)
- r.routers[m] = t
- }
- r.add(m, pattern, leaf)
- }
- return &Route{r, leaf}
- }
- func (r *Router) Handle(method string, pattern string, handlers []Handler) *Route {
- if len(r.groups) > 0 {
- groupPattern := ""
- h := make([]Handler, 0)
- for _, g := range r.groups {
- groupPattern += g.pattern
- h = append(h, g.handlers...)
- }
- pattern = groupPattern + pattern
- h = append(h, handlers...)
- handlers = h
- }
- handlers = validateAndWrapHandlers(handlers, r.handlerWrapper)
- return r.handle(method, pattern, func(resp http.ResponseWriter, req *http.Request, params Params) {
- c := r.m.createContext(resp, req)
- c.params = params
- c.handlers = make([]Handler, 0, len(r.m.handlers)+len(handlers))
- c.handlers = append(c.handlers, r.m.handlers...)
- c.handlers = append(c.handlers, handlers...)
- c.run()
- })
- }
- func (r *Router) Group(pattern string, fn func(), h ...Handler) {
- r.groups = append(r.groups, group{pattern, h})
- fn()
- r.groups = r.groups[:len(r.groups)-1]
- }
- func (r *Router) Get(pattern string, h ...Handler) (leaf *Route) {
- leaf = r.Handle("GET", pattern, h)
- if r.autoHead {
- r.Head(pattern, h...)
- }
- return leaf
- }
- func (r *Router) Patch(pattern string, h ...Handler) *Route {
- return r.Handle("PATCH", pattern, h)
- }
- func (r *Router) Post(pattern string, h ...Handler) *Route {
- return r.Handle("POST", pattern, h)
- }
- func (r *Router) Put(pattern string, h ...Handler) *Route {
- return r.Handle("PUT", pattern, h)
- }
- func (r *Router) Delete(pattern string, h ...Handler) *Route {
- return r.Handle("DELETE", pattern, h)
- }
- func (r *Router) Options(pattern string, h ...Handler) *Route {
- return r.Handle("OPTIONS", pattern, h)
- }
- func (r *Router) Head(pattern string, h ...Handler) *Route {
- return r.Handle("HEAD", pattern, h)
- }
- func (r *Router) Any(pattern string, h ...Handler) *Route {
- return r.Handle("*", pattern, h)
- }
- func (r *Router) Route(pattern, methods string, h ...Handler) (route *Route) {
- for _, m := range strings.Split(methods, ",") {
- route = r.Handle(strings.TrimSpace(m), pattern, h)
- }
- return route
- }
- func (r *Router) Combo(pattern string, h ...Handler) *ComboRouter {
- return &ComboRouter{r, pattern, h, map[string]bool{}, nil}
- }
- func (r *Router) NotFound(handlers ...Handler) {
- handlers = validateAndWrapHandlers(handlers)
- r.notFound = func(rw http.ResponseWriter, req *http.Request) {
- c := r.m.createContext(rw, req)
- c.handlers = make([]Handler, 0, len(r.m.handlers)+len(handlers))
- c.handlers = append(c.handlers, r.m.handlers...)
- c.handlers = append(c.handlers, handlers...)
- c.run()
- }
- }
- func (r *Router) InternalServerError(handlers ...Handler) {
- handlers = validateAndWrapHandlers(handlers)
- r.internalServerError = func(c *Context, err error) {
- c.index = 0
- c.handlers = handlers
- c.Map(err)
- c.run()
- }
- }
- func (r *Router) SetHandlerWrapper(f func(Handler) Handler) {
- r.handlerWrapper = f
- }
- func (r *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
- if t, ok := r.routers[req.Method]; ok {
-
- leaf := r.getLeaf(req.Method, req.URL.Path)
- if leaf != nil {
- leaf.handle(rw, req, nil)
- return
- }
- h, p, ok := t.Match(req.URL.EscapedPath())
- if ok {
- if splat, ok := p["*0"]; ok {
- p["*"] = splat
- }
- h(rw, req, p)
- return
- }
- }
- r.notFound(rw, req)
- }
- func (r *Router) URLFor(name string, pairs ...string) string {
- leaf, ok := r.namedRoutes[name]
- if !ok {
- panic("route with given name does not exists: " + name)
- }
- return leaf.URLPath(pairs...)
- }
- type ComboRouter struct {
- router *Router
- pattern string
- handlers []Handler
- methods map[string]bool
- lastRoute *Route
- }
- func (cr *ComboRouter) checkMethod(name string) {
- if cr.methods[name] {
- panic("method '" + name + "' has already been registered")
- }
- cr.methods[name] = true
- }
- func (cr *ComboRouter) route(fn func(string, ...Handler) *Route, method string, h ...Handler) *ComboRouter {
- cr.checkMethod(method)
- cr.lastRoute = fn(cr.pattern, append(cr.handlers, h...)...)
- return cr
- }
- func (cr *ComboRouter) Get(h ...Handler) *ComboRouter {
- if cr.router.autoHead {
- cr.Head(h...)
- }
- return cr.route(cr.router.Get, "GET", h...)
- }
- func (cr *ComboRouter) Patch(h ...Handler) *ComboRouter {
- return cr.route(cr.router.Patch, "PATCH", h...)
- }
- func (cr *ComboRouter) Post(h ...Handler) *ComboRouter {
- return cr.route(cr.router.Post, "POST", h...)
- }
- func (cr *ComboRouter) Put(h ...Handler) *ComboRouter {
- return cr.route(cr.router.Put, "PUT", h...)
- }
- func (cr *ComboRouter) Delete(h ...Handler) *ComboRouter {
- return cr.route(cr.router.Delete, "DELETE", h...)
- }
- func (cr *ComboRouter) Options(h ...Handler) *ComboRouter {
- return cr.route(cr.router.Options, "OPTIONS", h...)
- }
- func (cr *ComboRouter) Head(h ...Handler) *ComboRouter {
- return cr.route(cr.router.Head, "HEAD", h...)
- }
- func (cr *ComboRouter) Name(name string) {
- if cr.lastRoute == nil {
- panic("no corresponding route to be named")
- }
- cr.lastRoute.Name(name)
- }
|