From bf16415594f877bfa26714b17615d4beb067e0f6 Mon Sep 17 00:00:00 2001 From: nolwn Date: Sun, 22 Nov 2020 19:12:27 -0800 Subject: [PATCH] Save path segments that start with a : as variables --- router.go | 37 ++++++++++++++++++++++++++++++------- 1 file changed, 30 insertions(+), 7 deletions(-) diff --git a/router.go b/router.go index fcaf98a..03b98fc 100644 --- a/router.go +++ b/router.go @@ -18,22 +18,22 @@ import ( // parameter called "itemid". A request path with "/items/" followed by a string of legal http // characters, not including a slash, would match this path. type Router struct { - routes []route - root *segment - NotFoundHandler http.Handler + root *segment + routes []route } type route struct { + callback http.HandlerFunc method string path string - callback http.HandlerFunc } type segment struct { - path string - methods map[string]http.HandlerFunc children map[string]*segment + methods map[string]http.HandlerFunc + path string + variable string } // NotFoundHandler is the default function for handling routes that are not found. If you wish to @@ -79,7 +79,7 @@ func (r *Router) AddRoute(method string, path string, callback http.HandlerFunc) } curr.methods[method] = callback - r.routes = append(r.routes, route{method, path, callback}) + r.routes = append(r.routes, route{callback, method, path}) return } @@ -158,16 +158,24 @@ func addSegment(curr *segment, keys []string) (seg *segment) { func newSegment(parentPath string, key string) (seg *segment) { var path string + if parentPath == "/" { path = key + } else { path = parentPath + key } + seg = &segment{} + seg.children = map[string]*segment{} seg.methods = map[string]http.HandlerFunc{} seg.path = path + if isVariable(key) { + seg.variable = key[1:] + } + return } @@ -181,3 +189,18 @@ func setupKeys(slice []string) (keys []string) { return } + +// isVariable returns true if the key is more than one character long and starts with a ':' +func isVariable(key string) (isVar bool) { + if len(key) <= 1 { + return // avoid empty variables, i.e. /somepath/:/someotherpath + } + + if key[0] != ':' { + return + } + + isVar = true + + return +}