1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| type Router struct { roots map[string]*node handlers map[string]HandlerFunc }
func parsePattern(pattern string) []string { vs := strings.Split(pattern, "/")
parts := make([]string, 0) for _, item := range vs { if item != "" { parts = append(parts, item) if item[0] == '*' { break } } }
return parts }
func (router *Router) addRoute(method string, pattern string, handler HandlerFunc) { parts := parsePattern(pattern)
_, ok := router.roots[method] if !ok { router.roots[method] = &node{} } router.roots[method].insert(pattern, parts, 0)
key := method + "-" + pattern router.handlers[key] = handler }
func (router *Router) getRoute(method string, path string) (*node, map[string]string) { searchParts := parsePattern(path) params := make(map[string]string)
root, ok := router.roots[method] if !ok { return nil, nil }
n := root.search(searchParts, 0) if n != nil { parts := parsePattern(n.pattern) for index, part := range parts { if part[0] == ':' { params[part[1:]] = searchParts[index] } if part[0] == '*' && len(part) > 1 { params[part[1:]] = strings.Join(searchParts[index:], "/") break } } return n, params }
return nil, nil }
func (router *Router) handle(c *Context) { n, params := router.getRoute(c.Method, c.Path) if n != nil { c.Params = params key := c.Method + "-" + n.pattern router.handlers[key](c) } else { c.String(http.StatusNotFound, "404 NOT FOUND: %s\n", c.Path) } }
|