Compare commits

...

10 Commits

Author SHA1 Message Date
d5c2c1ddf2 Move to nolwn account. 2021-07-19 21:13:03 -07:00
19d616162f Fix messed up default 404. 2020-12-15 00:38:09 -08:00
05f90673c5 Clean unneeded Handle function. 2020-12-14 23:55:23 -08:00
0a6b9b2d0a ServeHTTP cannot take a pointer receiver 2020-12-13 23:26:09 -08:00
ee0bb08b57 Store path params in request context. 2020-12-13 22:57:01 -08:00
ac8a5ff56e Make Handler exported. 2020-12-09 23:33:48 -08:00
3e7625bbeb PathParams not a method on router 2020-12-09 22:44:50 -08:00
df7e3ccc03 Use request contex 2020-12-09 22:34:43 -08:00
08228b2aa7 Add cursory readme and MIT license. 2020-12-07 20:52:23 -08:00
1805ac77fe Add PathParams method. 2020-12-06 22:32:39 -08:00
5 changed files with 275 additions and 89 deletions

29
README.md Normal file
View File

@ -0,0 +1,29 @@
# Go Router
```go
type Router struct {
NotFoundHandler http.Handler
}
```
## Setting path params
Register routes with Router.AddRoute. Parts of the URI which start with a ":" are parameters. For example, if you registered `/user/:userID`, it would match `example.com/user/3`. You would then get a param called `userID` which would equal `"3"`.
Inside the handler function you provide, access path parameters with the `PathParams` function.
```go
router.AddRoute(http.MethodGet, "user/:userID", func(w http.ResponseWriter, r *http.Request) {
params, _ := PathParams(r)
userID := params["userID"]
})
```
## Not Found Handler
If Router.NotFoundHandler is not a set, a default handler will be called when a route is not found. If you want to set your own handler, set Router.NotFoundHandler with the http.Handler you would prefer.
## Public consumption
I have included a license but this really isn't for public consumption. If you have found this repository somehow and you want to use it, understand that you are on your own in terms of getting it working, fixing issues, adding features, etc. Use at your own risk.

4
go.mod
View File

@ -1,3 +1,3 @@
module github.com/jr-dev-league/go-router module github.com/nolwn/go-router
go 1.14 go 1.15

7
license Normal file
View File

@ -0,0 +1,7 @@
Copyright 2020 Nolan Hellyer
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

200
router.go
View File

@ -1,11 +1,14 @@
package router package router
import ( import (
"context"
"errors" "errors"
"net/http" "net/http"
"strings" "strings"
) )
type contextKey string
// Router is a replacement for the net/http DefaultServerMux. This version includes the // Router is a replacement for the net/http DefaultServerMux. This version includes the
// ability to add path parameter in the given path. // ability to add path parameter in the given path.
// //
@ -23,20 +26,40 @@ type Router struct {
routes []route routes []route
} }
// endpoint is comes at the end of each valid path in the tree. It contains the information you
// need to call the endpoint, including path parameter names.
type endpoint struct {
callback http.HandlerFunc
path string
pathParams []string
}
// parameter contains a pointer to a parameter segment and the name of the parameter.
type parameter struct {
name string
segment *segment
}
// route is not part of the tree, but is saved on the router to represent all the available
// routes in the tree.
type route struct { type route struct {
callback http.HandlerFunc callback http.HandlerFunc
method string method string
path string path string
} }
// segment is a tree node. It can have children, or endpoints, or both attached to it. It also
// has a special child called "parameter" which represents a path parameter. If a route string
// doesn't match any of the children, and there is a parameter child present, it will match that
// parameter child.
type segment struct { type segment struct {
children map[string]*segment children map[string]*segment
methods map[string]http.HandlerFunc endpoints map[string]*endpoint
path string parameter parameter
parameter *segment
parameterName string
} }
var paramsKey = contextKey("params")
// 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
// provide your own handler for this, simply set it on the router. // provide your own handler for this, simply set it on the router.
var NotFoundHandler http.Handler = http.HandlerFunc( var NotFoundHandler http.Handler = http.HandlerFunc(
@ -49,12 +72,12 @@ var NotFoundHandler http.Handler = http.HandlerFunc(
// method already have a callback registered to them, an error is returned. // method already have a callback registered to them, an error is returned.
func (r *Router) AddRoute(method string, path string, callback http.HandlerFunc) (err error) { func (r *Router) AddRoute(method string, path string, callback http.HandlerFunc) (err error) {
keys := setupKeys(strings.Split(path, "/")) keys := setupKeys(strings.Split(path, "/"))
pathParams := []string{}
if r.root == nil { if r.root == nil {
r.root = &segment{} r.root = &segment{}
r.root.children = map[string]*segment{} r.root.children = map[string]*segment{}
r.root.methods = map[string]http.HandlerFunc{} r.root.endpoints = map[string]*endpoint{}
r.root.path = "/"
} }
curr := r.root curr := r.root
@ -64,7 +87,12 @@ func (r *Router) AddRoute(method string, path string, callback http.HandlerFunc)
continue continue
} }
if child, ok := curr.children[key]; !ok { if isParameter(key) {
pathParams = append(pathParams, key[2:])
}
if child, _ := getChild(key, curr); child == nil {
seg := addSegment(curr, key) seg := addSegment(curr, key)
curr = seg curr = seg
} else { } else {
@ -72,65 +100,18 @@ func (r *Router) AddRoute(method string, path string, callback http.HandlerFunc)
} }
} }
if _, ok := curr.methods[method]; ok { if _, ok := curr.endpoints[method]; ok {
err = errors.New("path already exists") err = errors.New("path already exists")
return return
} }
curr.methods[method] = callback curr.endpoints[method] = &endpoint{callback, path, pathParams}
r.routes = append(r.routes, route{callback, method, path}) r.routes = append(r.routes, route{callback, method, path})
return return
} }
// Get is a convinience method which calls Router.AddRoute with the "GET" method.
func (r *Router) Get(path string, callback http.HandlerFunc) {
r.AddRoute(http.MethodGet, path, callback)
}
// Handler returns the handler to use for the given request, consulting r.Method, r.URL.Path. It
// always returns a non-nil handler.
//
// Handler also returns the registered pattern that matches the request.
//
// If there is no registered handler that applies to the request, Handler returns a ``page not
// found'' handler and an empty pattern.
func (r *Router) Handler(req *http.Request) (h http.Handler, pattern string) {
method := req.Method
path := req.URL.Path
root := r.root
curr := root
segments := strings.Split(path, "/")
keys := setupKeys(segments)
if r.NotFoundHandler == nil {
h = NotFoundHandler
}
for _, v := range keys {
if v == "/" {
continue
}
seg := getChild(v, curr)
if seg == nil {
return
}
curr = seg
}
if cb, ok := curr.methods[method]; ok {
h = cb
pattern = curr.path
}
return
}
// ServeHTTP is the function that is required by http.Handler. It takes an http.ResponseWriter which // ServeHTTP is the function that is required by http.Handler. It takes an http.ResponseWriter which
// it uses to write to a response object that will construct a response for the user. It also takes // it uses to write to a response object that will construct a response for the user. It also takes
// an *http.Request which describes the request the user has made. // an *http.Request which describes the request the user has made.
@ -138,24 +119,49 @@ func (r *Router) Handler(req *http.Request) (h http.Handler, pattern string) {
// In the case of this router, all it needs to do is lookup the Handler that has been saved at a given // In the case of this router, all it needs to do is lookup the Handler that has been saved at a given
// path and then call its ServeHTTP. // path and then call its ServeHTTP.
func (r Router) ServeHTTP(w http.ResponseWriter, req *http.Request) { func (r Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
handler, _ := r.Handler(req) method := req.Method
path := req.URL.Path
var handler http.Handler
endpoint, params, err := r.getEndpoint(method, path)
if err != nil {
if r.NotFoundHandler != nil {
handler = r.NotFoundHandler
} else {
handler = NotFoundHandler
}
} else {
handler = endpoint.callback
ctx := context.WithValue(context.Background(), paramsKey, params)
req = req.WithContext(ctx)
}
handler.ServeHTTP(w, req) handler.ServeHTTP(w, req)
}
// PathParams takes a path and returns the values for any path parameters
// in the path.
func PathParams(req *http.Request) (params map[string]string) {
params = req.Context().Value(paramsKey).(map[string]string)
return return
} }
// addSegment create a new segment either as a child or as a parameter depending on whether the key
// qualifies as a parameter. A pointer to the created segment is then returned.
func addSegment(curr *segment, key string) (seg *segment) { func addSegment(curr *segment, key string) (seg *segment) {
if curr.parameterName == key { if curr.parameter.segment != nil {
seg = curr.parameter seg = curr.parameter.segment
} else if child, ok := curr.children[key]; !ok { // child does not match... } else if child, ok := curr.children[key]; !ok { // child does not match...
var isParam bool var isParam bool
seg, isParam = newSegment(curr.path, key) seg, isParam = newSegment(key)
if isParam { if isParam {
curr.parameter = seg curr.parameter.segment = seg
curr.parameterName = key[2:] curr.parameter.name = key[2:]
} else { } else {
curr.children[key] = seg curr.children[key] = seg
@ -170,33 +176,69 @@ func addSegment(curr *segment, key string) (seg *segment) {
return return
} }
func getChild(key string, curr *segment) (child *segment) { // getChild takes a path part and finds the appropriate segment child for it. If it is an exact match to a
if seg, ok := curr.children[key]; ok { // is there an exact match? // child on the segment, then that child segment is returned. If it is not a match, then the parameter child
// is returned. If there is no parameter child, nil is returned. isParam is true if the parameter child is
// being returned.
func getChild(key string, curr *segment) (child *segment, param string) {
if curr == nil {
return
} else if seg, ok := curr.children[key]; ok { // is there an exact match?
child = seg child = seg
} else if curr.parameter != nil { // could this be a parameter?
child = curr.parameter
} else if curr.parameter.segment != nil { // could this be a parameter?
child = curr.parameter.segment
param = curr.parameter.name
} }
return return
} }
func newSegment(parentPath string, key string) (seg *segment, isParam bool) { // getEndpoint takes a path and traverses the tree until it finds the endpoint associated with that path.
var path string // If no endpoint if found, an error is returned.
func (r *Router) getEndpoint(method string, path string) (end *endpoint, params map[string]string, err error) {
curr := r.root
segments := strings.Split(path, "/")
params = map[string]string{}
keys := setupKeys(segments)
if parentPath == "/" { for _, key := range keys {
path = key if key == "/" {
continue
}
} else { seg, paramName := getChild(key, curr)
path = parentPath + key
if seg == nil {
err = errors.New("route not found")
return
}
if paramName != "" {
params[paramName] = key[1:]
}
curr = seg
} }
if _, ok := curr.endpoints[method]; !ok {
err = errors.New("route not found")
}
end = curr.endpoints[method]
return
}
// TODO: refactor out newSegment as it's not longer needed.
// newSegment constructs a new, empty segment and reports back if the key is a parameter.
func newSegment(key string) (seg *segment, isParam bool) {
seg = &segment{} seg = &segment{}
seg.children = map[string]*segment{} seg.children = map[string]*segment{}
seg.methods = map[string]http.HandlerFunc{} seg.endpoints = map[string]*endpoint{}
seg.path = path
if isParameter(key) { if isParameter(key) {
isParam = true isParam = true
@ -205,6 +247,8 @@ func newSegment(parentPath string, key string) (seg *segment, isParam bool) {
return return
} }
// setupKeys takes an array of strings representing the parts of a path, and returns a new slice
// made up of the parts with "/" prepended to each.
func setupKeys(slice []string) (keys []string) { func setupKeys(slice []string) (keys []string) {
keys = append(keys, "/") keys = append(keys, "/")
for _, v := range slice { for _, v := range slice {
@ -217,8 +261,8 @@ func setupKeys(slice []string) (keys []string) {
} }
// isParameter returns true if the key is more than one character long and starts with a ':' // isParameter returns true if the key is more than one character long and starts with a ':'
func isParameter(key string) (isVar bool) { func isParameter(key string) (isParam bool) {
if len([]rune(key)) <= 2 { if len([]rune(key)) <= 1 {
return // avoid empty variables, i.e. /somepath/:/someotherpath return // avoid empty variables, i.e. /somepath/:/someotherpath
} }
@ -226,7 +270,7 @@ func isParameter(key string) (isVar bool) {
return return
} }
isVar = true isParam = true
return return
} }

View File

@ -11,24 +11,34 @@ import (
var testLevel = 1 var testLevel = 1
func TestAddRouter(t *testing.T) { func TestAddRouter(t *testing.T) {
describeTests("Test AddRouter function") describeTests("Test AddRouter method")
router := Router{} router := Router{}
testAddRoot(router, t) testAddRoot(router, t)
testAddOneSegment(router, t) testAddOneSegment(router, t)
testAddManySegments(router, t) testAddManySegments(router, t)
// TODO: add test for error when trying duplicate method + path testAddDuplicateEndpoint(router, t)
} }
func TestServeHTTP(t *testing.T) { func TestServeHTTP(t *testing.T) {
describeTests("Test ServeHTTP function") describeTests("Test ServeHTTP method")
router := Router{} router := Router{}
testMatchesRoot(router, t) testMatchesRoot(router, t)
testMatchesLongPath(router, t) testMatchesLongPath(router, t)
testMatchesPathParam(router, t) testMatchesPathParam(router, t)
testDefaultNotFound(router, t)
testCustomNotFound(router, t)
}
func TestPathParams(t *testing.T) {
describeTests("Test PathParams method")
router := Router{}
testParamValues(router, t)
} }
func addAndCheckRoute(r *Router, method string, path string, callback http.HandlerFunc) (err error) { func addAndCheckRoute(r *Router, method string, path string, callback http.HandlerFunc) (err error) {
@ -71,14 +81,14 @@ func addAndCheckRoute(r *Router, method string, path string, callback http.Handl
// checkLookup prints out the various saved routes. It's not needed for any test, but is a helpful debugging tool. // checkLookup prints out the various saved routes. It's not needed for any test, but is a helpful debugging tool.
func checkLookup(curr *segment) { func checkLookup(curr *segment) {
fmt.Printf("%p { path: \"%s\", methods: %v, children: %v, parameter: %v, parameterName: \"%s\"}\n", curr, curr.path, curr.methods, curr.children, curr.parameter, curr.parameterName) fmt.Printf("%p { methods: %v, children: %v, parameter: %v\"}\n", curr, curr.endpoints, curr.children, curr.parameter)
for _, v := range curr.children { for _, v := range curr.children {
checkLookup(v) checkLookup(v)
} }
if curr.parameter != nil { if curr.parameter.segment != nil {
checkLookup(curr.parameter) checkLookup(curr.parameter.segment)
} }
} }
@ -100,7 +110,7 @@ func matchAndCheckRoute(r *Router, method string, path string, expectedBody stri
r.ServeHTTP(rr, request) r.ServeHTTP(rr, request)
if rr.Code != expectedCode { if rr.Code != expectedCode {
err = fmt.Errorf("The returned callback did not write 200 to the header. Found %d", rr.Code) err = fmt.Errorf("The returned callback did not write %d to the header. Found %d", expectedCode, rr.Code)
return return
} }
@ -120,6 +130,28 @@ func matchAndCheckRoute(r *Router, method string, path string, expectedBody stri
return return
} }
func testAddDuplicateEndpoint(router Router, t *testing.T) {
defer testOutcome("add duplicate endpoints", t)
err := addAndCheckRoute(&router, http.MethodGet, "/dupe", func(http.ResponseWriter, *http.Request) {})
if err != nil {
t.Error("The route was not correctly added to the routoer", err)
}
err = addAndCheckRoute(&router, http.MethodPost, "/dupe", func(http.ResponseWriter, *http.Request) {})
if err != nil {
t.Error("The route was not correctly added to the routoer", err)
}
err = addAndCheckRoute(&router, http.MethodGet, "/dupe", func(http.ResponseWriter, *http.Request) {})
if err == nil {
t.Error("Adding a duplicate route should throw an error.")
}
}
func testAddManySegments(router Router, t *testing.T) { func testAddManySegments(router Router, t *testing.T) {
defer testOutcome("add many multiple segments", t) defer testOutcome("add many multiple segments", t)
@ -162,6 +194,43 @@ func testAddRoot(router Router, t *testing.T) {
} }
} }
func testCustomNotFound(router Router, t *testing.T) {
defer testOutcome("custom NotFoundHandler", t)
expectedBody := "Forbidden"
expectedCode := 401
path := "/gibberish/forbidden"
router.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(expectedCode)
w.Write([]byte(expectedBody))
})
err := matchAndCheckRoute(&router, http.MethodPatch, path, expectedBody, expectedCode)
if err != nil {
t.Error("Did not call the custom handler.", err)
return
}
}
func testDefaultNotFound(router Router, t *testing.T) {
defer testOutcome("default NotFoundHandler", t)
expectedBody := "Not Found."
expectedCode := 404
path := "/gibberish"
err := matchAndCheckRoute(&router, http.MethodDelete, path, expectedBody, expectedCode)
if err != nil {
t.Error("Did not find the expected callback handler", err)
return
}
}
func testMatchesLongPath(router Router, t *testing.T) { func testMatchesLongPath(router Router, t *testing.T) {
defer testOutcome("match long path", t) defer testOutcome("match long path", t)
@ -226,6 +295,45 @@ func testMatchesRoot(router Router, t *testing.T) {
} }
} }
func testParamValues(router Router, t *testing.T) {
defer testOutcome("returns param names and values", t)
method := http.MethodOptions
path := "/users/:userID/edit/:status"
userID := "46"
status := "inactive"
expectedBody := "done"
expectedStatus := 200
reqPath := fmt.Sprintf("/users/%s/edit/%s", userID, status)
router.AddRoute(method, path, func(w http.ResponseWriter, r *http.Request) {
params := PathParams(r)
if len(params) != 2 {
t.Errorf("Received the wrong number of parameters. Expected 2, recieved %d", len(params))
}
if params["userID"] != userID {
t.Errorf("userID should be %s, but it is %s", userID, params["userID"])
}
if params["status"] != status {
t.Errorf("status should be %s, but it is %s", status, params["status"])
}
w.WriteHeader(expectedStatus)
w.Write([]byte(expectedBody))
})
err := matchAndCheckRoute(&router, method, reqPath, expectedBody, expectedStatus)
if err != nil {
t.Error("Did not find the expected callback handler", err)
return
}
}
func testOutcome(message string, t *testing.T) { func testOutcome(message string, t *testing.T) {
var status string var status string
@ -236,6 +344,4 @@ func testOutcome(message string, t *testing.T) {
} }
fmt.Printf("\t%s %s\n", status, message) fmt.Printf("\t%s %s\n", status, message)
return
} }