Save path segments that start with a : as variables

This commit is contained in:
2020-11-22 19:12:27 -08:00
parent 5a002e8f9b
commit bf16415594

View File

@ -18,22 +18,22 @@ import (
// parameter called "itemid". A request path with "/items/" followed by a string of legal http // parameter called "itemid". A request path with "/items/" followed by a string of legal http
// characters, not including a slash, would match this path. // characters, not including a slash, would match this path.
type Router struct { type Router struct {
routes []route
root *segment
NotFoundHandler http.Handler NotFoundHandler http.Handler
root *segment
routes []route
} }
type route struct { type route struct {
callback http.HandlerFunc
method string method string
path string path string
callback http.HandlerFunc
} }
type segment struct { type segment struct {
path string
methods map[string]http.HandlerFunc
children map[string]*segment 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 // 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 curr.methods[method] = callback
r.routes = append(r.routes, route{method, path, callback}) r.routes = append(r.routes, route{callback, method, path})
return return
} }
@ -158,16 +158,24 @@ func addSegment(curr *segment, keys []string) (seg *segment) {
func newSegment(parentPath string, key string) (seg *segment) { func newSegment(parentPath string, key string) (seg *segment) {
var path string var path string
if parentPath == "/" { if parentPath == "/" {
path = key path = key
} else { } else {
path = parentPath + key path = parentPath + key
} }
seg = &segment{} seg = &segment{}
seg.children = map[string]*segment{} seg.children = map[string]*segment{}
seg.methods = map[string]http.HandlerFunc{} seg.methods = map[string]http.HandlerFunc{}
seg.path = path seg.path = path
if isVariable(key) {
seg.variable = key[1:]
}
return return
} }
@ -181,3 +189,18 @@ func setupKeys(slice []string) (keys []string) {
return 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
}