-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathstackr.go
More file actions
294 lines (224 loc) · 5.31 KB
/
stackr.go
File metadata and controls
294 lines (224 loc) · 5.31 KB
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
/*
Stackr is an extensible HTTP server framework for Go.
package main
import "github.com/ricallinson/stackr"
func main() {
app := stackr.CreateServer()
app.Use(stackr.Logger())
app.Use(stackr.Static())
app.Use("/", func(req *stackr.Request, res *stackr.Response, next func()) {
res.End("hello world\n")
})
app.Listen(3000)
}
*/
package stackr
import (
"errors"
"fmt"
"log"
"net/http"
"os"
"strings"
)
/*
A Stackr Server.
*/
type Server struct {
Env string
stack []middleware
}
/*
A middleware.
*/
type middleware struct {
Route string
Handle func(*Request, *Response, func())
}
/*
Create a new stackr server.
*/
func CreateServer() *Server {
this := &Server{}
this.Env = os.Getenv("GO_ENV")
if this.Env == "" {
this.Env = "development"
}
return this
}
/*
Utilize the given middleware `Handle` to the given `route`,
defaulting to _/_. This "route" is the mount-point for the
middleware, when given a value other than _/_ the middleware
is only effective when that segment is present in the request's
pathname.
For example if we were to mount a function at _/admin_, it would
be invoked on _/admin_, and _/admin/settings_, however it would
not be invoked for _/_, or _/posts_.
Examples:
var app = stackr.CreateServer();
app.Use(stackr.Favicon())
app.Use(stackr.Logger())
app.Use("/public", stackr.Static())
If we wanted to prefix static files with _/public_, we could
"mount" the `Static()` middleware:
app.Use("/public", stackr.Static(stackr.OptStatic{Root: "./static_files"}))
This api is chainable, so the following is valid:
stackr.CreateServer().Use(stackr.Favicon()).Listen(3000);
*/
func (this *Server) Use(in ...interface{}) *Server {
var route string
var handle func(*Request, *Response, func())
for _, i := range in {
switch i.(type) {
case string:
route = i.(string)
case func(*Request, *Response, func()):
handle = i.(func(*Request, *Response, func()))
default:
panic("stackr: Go home handler, you're drunk!")
}
}
/*
If the route is empty make it "/".
*/
if len(route) == 0 {
route = "/"
}
/*
Strip trailing slash
*/
if size := len(route); size > 1 && route[size-1] == '/' {
route = route[:size-1]
}
/*
Add the middleware to the stack.
*/
this.stack = append(this.stack, middleware{
Route: strings.ToLower(route),
Handle: handle,
})
/*
Return the Server so calls can be chained.
*/
return this
}
/*
Handle server requests, punting them down
the middleware stack.
Note: this is a recursive function.
*/
func (this *Server) Handle(req *Request, res *Response, index int) {
/*
For each call to Handle we want to catch anything that panics unless in development mode.
*/
defer func() {
if this.Env != "development" {
err := recover()
if err != nil {
res.Error = errors.New(fmt.Sprint(err))
}
}
}()
/*
If the response has been closed return.
*/
if res.Closed == true {
return
}
/*
Create a var for the middleware.
*/
var layer middleware
/*
Do we have another layer to use?
*/
if index >= len(this.stack) {
layer = middleware{} // no
} else {
layer = this.stack[index] // yes
index++ // increment the index by 1
}
/*
If there are no more layers and no headers have been sent return a 404.
*/
if layer.Handle == nil && res.HeaderSent == false {
res.StatusCode = 404
res.SetHeader("Content-Type", "text/plain")
if req.Method == "HEAD" {
res.End("")
return
}
res.End("Cannot " + fmt.Sprint(req.Method) + " " + fmt.Sprint(req.OriginalUrl))
return
}
/*
If there are no more layers and headers were sent then we are done so just return.
*/
if layer.Handle == nil {
return
}
/*
Otherwise call the layer Handler.
*/
if strings.Contains(req.OriginalUrl, layer.Route) {
/*
Set the value of Url to the portion after the matched layer.Route
*/
req.Url = strings.TrimPrefix(req.OriginalUrl, layer.Route)
/*
Set the matched portion of the Url.
*/
req.MatchedUrl = layer.Route
/*
Call the middleware function.
*/
layer.Handle(req, res, func() {
/*
The value of next is a function that calls this function again, passing the index value.
*/
this.Handle(req, res, index)
})
} else {
/*
Call this function, passing the index value.
*/
this.Handle(req, res, index)
}
}
/*
ServeHTTP calls .Handle(req, res).
*/
func (this *Server) ServeHTTP(res http.ResponseWriter, req *http.Request) {
/*
Pass the res and req into there repective create functions.
The results of these are then passed to stack.server.Handle().
*/
this.Handle(createRequest(req), createResponse(res), 0)
}
/*
Listen for connections on HTTP.
*/
func (this *Server) Listen(port int) {
/*
Set the address to run on.
*/
address := ":" + fmt.Sprint(port)
/*
Start the server by mapping all URLs into this Server.
*/
log.Fatal(http.ListenAndServe(address, this))
}
/*
Listen for connections on HTTPS.
*/
func (this *Server) ListenTLS(port int, certFile string, keyFile string) {
/*
Set the address to run on.
*/
address := ":" + fmt.Sprint(port)
/*
Start the server by mapping all URLs into this Server.
*/
log.Fatal(http.ListenAndServeTLS(address, certFile, keyFile, this))
}