This repository was archived by the owner on Mar 16, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathrouter.go
105 lines (80 loc) · 2.28 KB
/
router.go
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package goat
import (
"net/http"
"github.com/julienschmidt/httprouter"
)
// Router represents a router
type Router struct {
// Tree structure
parent *Router
children []*Router
// The prefix, default: /
prefix string
// The index, maps titles to urls
index map[string]string
// The router
router *httprouter.Router
// Middleware
middleware []Middleware
}
// Handle describes the function that should be used by handlers
type Handle func(http.ResponseWriter, *http.Request, Params)
// Subrouter creates and returns a subrouter
func (r *Router) Subrouter(path string) *Router {
sr := &Router{
index: make(map[string]string),
prefix: r.subPath(path),
router: r.router,
}
// Init relationships
r.children = append(r.children, sr)
sr.parent = r
return sr
}
// addRoute adds a route to the index and passes it over to the httprouter
func (r *Router) addRoute(m, p, t string, fn Handle) {
path := r.subPath(p)
// Add to index
if len(t) > 0 && m == "GET" {
// TODO: Display total path including host
r.index[t] = path
}
// Wrapper function to bypass the parameter problem
wf := func(w http.ResponseWriter, req *http.Request, p httprouter.Params) {
fn(w, req, paramsFromHTTPRouter(p))
}
r.router.Handle(m, path, wf)
}
// Get adds a GET route
func (r *Router) Get(path, title string, fn Handle) {
r.addRoute("GET", path, title, fn)
}
// Post adds a POST route
func (r *Router) Post(path, title string, fn Handle) {
r.addRoute("POST", path, title, fn)
}
// Delete adds a DELETE route
func (r *Router) Delete(path, title string, fn Handle) {
r.addRoute("DELETE", path, title, fn)
}
// Put adds a PUT route
func (r *Router) Put(path, title string, fn Handle) {
r.addRoute("PUT", path, title, fn)
}
// Options adds a OPTIONS route
func (r *Router) Options(path, title string, fn Handle) {
r.addRoute("OPTIONS", path, title, fn)
}
// notFoundHandler handles (as you already know) the 404 error
func (r *Router) notFoundHandler(w http.ResponseWriter, req *http.Request) {
WriteError(w, 404, "404 Not Found")
}
// subPath returns the prefix of the router + the given path and eliminates
// duplicate slashes
func (r *Router) subPath(p string) string {
pre := r.prefix
if (pre == "/" || pre[:len(pre)-1] == "/") && p[:1] == "/" {
pre = pre[:len(pre)-1]
}
return pre + p
}