-
Notifications
You must be signed in to change notification settings - Fork 4
/
goober.go
321 lines (271 loc) · 7.89 KB
/
goober.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
package goober
/*
* Funky fresh library brought to you by:
* Cole Brown
*
*/
import (
"net/http"
"strings"
"io"
"time"
"fmt"
"net/url"
)
// Main goober struct. Abides the handler interface.
type Goober struct {
head map[string]*routeTreeNode
ErrorPages map[int]string
}
// Goober handlers, for simplicity, are just functions with a given
// signature.
type Handler func(http.ResponseWriter, *Request)
type PipeHandler func(http.ResponseWriter, *Request) (error)
// We use this a few places, so we can give it a type as well.
type RouteMap map[string]*routeTreeNode
// Our parse tree structure for routes
type routeTreeNode struct {
handler Handler // Handler if a node is a terminal
pre []PipeHandler
post []PipeHandler
children RouteMap // Static children
variables RouteMap // Dynamic/variable children
}
// Chaining for pre/post handlers
func (n *routeTreeNode) AddPreFunc(f PipeHandler) (*routeTreeNode) {
n.pre = append(n.pre[:], f)
return n
}
func (n *routeTreeNode) AddPostFunc(f PipeHandler) (*routeTreeNode) {
n.post = append(n.post[:], f)
return n
}
// Augment http.Request with URLParams that will be grabbed
// from the request in the form of /:variables/
type Request struct {
http.Request
URLParams map[string]string
}
// A quick initializer for routeTreeNodes
func newRouteTreeNode() (node *routeTreeNode) {
node = &routeTreeNode{
children: make(RouteMap),
variables: make(RouteMap),
pre: []PipeHandler{},
post: []PipeHandler{},
}
return
}
// Initialize our Goober object
func New() (* Goober) {
var head = make(RouteMap)
head["GET"] = newRouteTreeNode()
head["HEAD"] = newRouteTreeNode()
head["POST"] = newRouteTreeNode()
head["PUT"] = newRouteTreeNode()
head["DELETE"] = newRouteTreeNode()
g := &Goober{
head: head,
ErrorPages: make(map[int]string),
}
return g
}
// Simple helper to allow us to trim leading and trailing /'s
func isSlash(s rune) (bool) {
return s == '/'
}
type BadRouteError struct {
Route string
Reason string
}
func (e BadRouteError) Error() string {
return "\"" + e.Route + "\" is an invalid route because " + e.Reason + "."
}
// Adds a handler to our route tree
func (g *Goober) AddHandler(method string, route string, handler Handler) (cur *routeTreeNode){
route = strings.TrimFunc(route, isSlash)
var parts = strings.Split(route, "/")
// Iterate through the bits of our path and add to the tree
cur = g.head[method]
// check to see if it's the root
if len(route) > 0 {
for i := range parts {
var part = parts[i]
// No // empty paths
if len(part) == 0 {
return nil
}
// Check for variables
if strings.HasPrefix(part, ":") {
// dynamic
if (cur.variables[part] != nil) {
cur = cur.variables[part]
} else {
cur.variables[part] = newRouteTreeNode()
cur = cur.variables[part]
}
} else {
// static
if (cur.children[part] != nil) {
cur = cur.children[part]
} else {
cur.children[part] = newRouteTreeNode()
cur = cur.children[part]
}
}
}
}
// add handler
cur.handler = handler
return
}
// Wrapper functions for common types of request
func (g *Goober) Get(route string, handler Handler) (node *routeTreeNode) {
return g.AddHandler("GET", route, handler)
}
func (g *Goober) Head(route string, handler Handler) (node *routeTreeNode) {
return g.AddHandler("HEAD", route, handler)
}
func (g *Goober) Post(route string, handler Handler) (node *routeTreeNode) {
return g.AddHandler("POST", route, handler)
}
func (g *Goober) Put(route string, handler Handler) (node *routeTreeNode) {
return g.AddHandler("PUT", route, handler)
}
func (g *Goober) Delete(route string, handler Handler) (node *routeTreeNode) {
return g.AddHandler("DELETE", route, handler)
}
type RouteNotFoundError struct {
Route string
}
func (e RouteNotFoundError) Error() string {
return "Route \"" + e.Route + "\" was not found."
}
func walkTree(node *routeTreeNode, parts []string, r *Request) (*routeTreeNode, error) {
var err error = nil
if len(parts) == 0 {
// if we've reached a terminal state, return node
if node.handler == nil {
err = &RouteNotFoundError{Route: r.URL.Path}
}
return node, err
} else {
// else, look for it
var part = parts[0]
if child, ok := node.children["*"]; ok {
node = child
r.URLParams["*"] = strings.Join(parts, "/")
} else if node.children[part] != nil {
// check static routes first, they have priority
return walkTree(node.children[part], parts[1:], r)
} else {
for k, v := range node.variables {
// check all dynamic routes, taking first match
node, err = walkTree(v, parts[1:], r)
if err == nil {
// goofy recursive way to build up params
r.URLParams[k] = part
return node, err
}
}
// if we don't find any dynamic matches, there was an error
err = &RouteNotFoundError{Route: r.URL.Path}
}
}
return node, err
}
// Given a request, find the appropriate handler
func (g *Goober) GetHandler(r *Request) (node *routeTreeNode, err error) {
path := strings.TrimFunc(r.URL.Path, isSlash)
// root case
if len(path) == 0 {
if g.head[r.Method].handler == nil {
err := &RouteNotFoundError{Route: r.URL.Path}
return g.head[r.Method], err
} else {
return g.head[r.Method], nil
}
}
parts := strings.Split(path, "/")
return walkTree(g.head[r.Method], parts, r)
}
// A simple function to handle error pages for us
func (g *Goober) errorHandler(w http.ResponseWriter, r *Request, code int) {
if page, ok := g.ErrorPages[code]; ok {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(code)
io.WriteString(w, page)
}
}
// Borrowed from web.go
func webTime(t time.Time) string {
ftime := t.Format(time.RFC1123)
if strings.HasSuffix(ftime, "UTC") {
ftime = ftime[0:len(ftime)-3] + "GMT"
}
return ftime
}
// Routes requests
func (g *Goober) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var startTime = time.Now()
defer func() {
fmt.Printf("[%s] %s - took %s\n", r.Method, r.URL.Path, time.Since(startTime))
r.Body.Close()
}()
// create augmented request object
var request = &Request{
Request: *r,
URLParams: make(map[string]string),
}
// get the handler for the request
node, err := g.GetHandler(request)
if err == nil {
// user response. pad with content-type.
//w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Server", "goober.go")
w.Header().Set("Date", webTime(time.Now().UTC()))
// Run prefunctions
for _, f := range node.pre {
if e := f(w, request); e != nil {
// if there is an error, print, 404 and exit out
fmt.Println("[ERROR] " + e.Error())
g.errorHandler(w, request, 404)
return
}
}
// Run the handler
node.handler(w, request)
// Run all postfunctions
for _, f := range node.post {
if e := f(w, request); e != nil {
// if there is an error, print and exit out
fmt.Println("[ERROR] " + e.Error())
return
}
}
} else {
fmt.Println("[ERROR] " + err.Error())
g.errorHandler(w, request, 404)
}
}
// Turns a http.HandlerFunc into a goober.Handler
func MakeHandler(f http.Handler) (Handler) {
return func (w http.ResponseWriter, r *Request) {
values := make(url.Values)
req := &r.Request
for k, v := range r.URLParams {
values.Set(k, v)
}
if len(req.URL.RawQuery) > 0 {
req.URL.RawQuery = values.Encode() + "&" + req.URL.RawQuery
} else {
req.URL.RawQuery = values.Encode()
}
f.ServeHTTP(w, req)
}
}
// shortcut to start serving a goober service
func (g *Goober) ListenAndServe(addr string) (err error) {
http.Handle("/", g)
return http.ListenAndServe(addr, nil)
}