forked from bubble-bot/weavebox
/
weavebox.go
464 lines (397 loc) · 13.6 KB
/
weavebox.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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
package weavebox
import (
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"os"
"path"
"runtime"
"time"
kitlog "github.com/go-kit/kit/log"
"github.com/julienschmidt/httprouter"
"golang.org/x/net/context"
)
// Package weavebox is opinion based minimalistic web framework for making fast and
// powerfull web application in the Go programming language. It is backed by
// the fastest and most optimized request router available. Weavebox also
// provides a gracefull webserver that can serve TLS encripted requests aswell.
var defaultErrorHandler = func(ctx *Context, err error) {
http.Error(ctx.Response(), err.Error(), http.StatusInternalServerError)
}
// Weavebox first class object that is created by calling New()
type Weavebox struct {
// ErrorHandler is invoked whenever a Handler returns an error
ErrorHandler ErrorHandlerFunc
// Output writes the access-log and debug parameters
Output io.Writer
// EnableAccessLog lets you turn of the default access-log
EnableAccessLog bool
// HTTP2 enables the HTTP2 protocol on the server. HTTP2 wil be default proto
// in the future. Currently browsers only supports HTTP/2 over encrypted TLS.
HTTP2 bool
templateEngine Renderer
router *httprouter.Router
middleware []Middleware
prefix string
context context.Context
logger kitlog.Logger
}
// New returns a new Weavebox object
func New() *Weavebox {
return &Weavebox{
router: httprouter.New(),
Output: os.Stderr,
ErrorHandler: defaultErrorHandler,
EnableAccessLog: false,
logger: kitlog.NewLogfmtLogger(os.Stderr),
}
}
// Serve serves the application on the given port
func (w *Weavebox) Serve(port int) error {
srv := newServer(fmt.Sprintf(":%d", port), w, w.HTTP2)
return w.serve(srv)
}
// ServeTLS serves the application one the given port with TLS encription.
func (w *Weavebox) ServeTLS(port int, certFile, keyFile string) error {
srv := newServer(fmt.Sprintf(":%d", port), w, w.HTTP2)
return w.serve(srv, certFile, keyFile)
}
// ServeCustom serves the application with custom server configuration.
func (w *Weavebox) ServeCustom(s *http.Server) error {
return w.serve(s)
}
// ServeCustomTLS serves the application with TLS encription and custom server configuration.
func (w *Weavebox) ServeCustomTLS(s *http.Server, certFile, keyFile string) error {
return w.serve(s, certFile, keyFile)
}
func (w *Weavebox) serve(s *http.Server, files ...string) error {
srv := &server{
Server: s,
quit: make(chan struct{}, 1),
fquit: make(chan struct{}, 1),
}
if len(files) == 0 {
fmt.Fprintf(w.Output, "app listening on 0.0.0.0:%s\n", s.Addr)
return srv.ListenAndServe()
}
if len(files) == 2 {
fmt.Fprintf(w.Output, "app listening TLS on 0.0.0.0:%s\n", s.Addr)
return srv.ListenAndServeTLS(files[0], files[1])
}
return errors.New("invalid server configuration")
}
// Handle adapts the usage of an http.Handler and will be invoked when
// the router matches the prefix and request method
func (w *Weavebox) Handle(method, path string, h http.Handler) {
w.router.Handler(method, path, h)
}
// Get registers a route prefix and will invoke the Handler when the route
// matches the prefix and the request METHOD is GET
func (w *Weavebox) Get(route string, h Handler) {
w.add("GET", route, h)
}
// Post registers a route prefix and will invoke the Handler when the route
// matches the prefix and the request METHOD is POST
func (w *Weavebox) Post(route string, h Handler) {
w.add("POST", route, h)
}
// Put registers a route prefix and will invoke the Handler when the route
// matches the prefix and the request METHOD is PUT
func (w *Weavebox) Put(route string, h Handler) {
w.add("PUT", route, h)
}
// Delete registers a route prefix and will invoke the Handler when the route
// matches the prefix and the request METHOD is DELETE
func (w *Weavebox) Delete(route string, h Handler) {
w.add("DELETE", route, h)
}
// Head registers a route prefix and will invoke the Handler when the route
// matches the prefix and the request METHOD is HEAD
func (w *Weavebox) Head(route string, h Handler) {
w.add("HEAD", route, h)
}
// Options registers a route prefix and will invoke the Handler when the route
// matches the prefix and the request METHOD is OPTIONS
func (w *Weavebox) Options(route string, h Handler) {
w.add("OPTIONS", route, h)
}
// Static registers the prefix to the router and start to act as a fileserver
// app.Static("/public", "./assets")
func (w *Weavebox) Static(prefix, dir string) {
w.router.ServeFiles(path.Join(prefix, "*filepath"), http.Dir(dir))
}
// BindContext lets you provide a context that will live a full http roundtrip
// BindContext is mostly used in a func main() to provide init variables that
// may be created only once, like a database connection. If BindContext is not
// called, weavebox will use a context.Background()
func (w *Weavebox) BindContext(ctx context.Context) {
w.context = ctx
}
// Middleware is decorator pattern for wrapping weavebox.Handler functions.
type Middleware func(Handler) Handler
// Use appends a Handler to the box middleware. Different middleware can be set
// for each subrouter (Box).
func (w *Weavebox) Use(handlers ...Middleware) {
for _, h := range handlers {
w.middleware = append(w.middleware, h)
}
}
// Box returns a new Box that will inherit all of its parents middleware.
// you can reset the middleware registered to the box by calling Reset()
func (w *Weavebox) Box(prefix string) *Box {
b := &Box{*w}
b.Weavebox.prefix += prefix
return b
}
// Box act as a subrouter and wil inherit all of its parents middleware
type Box struct {
Weavebox
}
// ResetMiddleware clears all middleware of a box
func (b *Box) ResetMiddleware() *Box {
b.Weavebox.middleware = nil
return b
}
// SetTemplateEngine allows the use of any template engine out there, if it
// satisfies the Renderer interface
func (w *Weavebox) SetTemplateEngine(t Renderer) {
w.templateEngine = t
}
// SetNotFoundHandler sets a custom handler that is invoked whenever the
// router could not match a route against the request url.
func (w *Weavebox) SetNotFoundHandler(h http.Handler) {
w.router.NotFound = h
}
// SetMethodNotAllowed sets a custom handler that is invoked whenever the router
// could not match the method against the predefined routes.
func (w *Weavebox) SetMethodNotAllowed(h http.Handler) {
w.router.MethodNotAllowed = h
}
// SetErrorHandler sets a centralized errorHandler that is invoked whenever
// a Handler returns an error.
func (w *Weavebox) SetErrorHandler(h ErrorHandlerFunc) {
w.ErrorHandler = h
}
// ServeHTTP satisfies the http.Handler interface
func (w *Weavebox) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
if rw != nil {
rw.Header().Set("Server", "weavebox/1.0")
}
if w.EnableAccessLog {
start := time.Now()
logger := &responseLogger{w: rw}
w.router.ServeHTTP(logger, r)
w.writeLog(r, start, logger.Status(), logger.Size())
// saves an allocation by seperating the whole logger if log is disabled
} else {
w.router.ServeHTTP(rw, r)
}
}
func (w *Weavebox) add(method, route string, h Handler) {
path := path.Join(w.prefix, route)
w.router.Handle(method, path, w.makeHTTPRouterHandle(h))
}
func (w *Weavebox) makeHTTPRouterHandle(h Handler) httprouter.Handle {
return func(rw http.ResponseWriter, r *http.Request, params httprouter.Params) {
if w.context == nil {
w.context = context.Background()
}
ctx := &Context{
Context: w.context,
vars: params,
response: rw,
request: r,
weavebox: w,
}
defer func() {
if err := recover(); err != nil {
trace := make([]byte, 256)
n := runtime.Stack(trace, true)
w.logger.Log("recoverd", err, "stacktrace", string(trace[:n]))
w.ErrorHandler(ctx, fmt.Errorf("%v", err))
return
}
}()
for i := len(w.middleware) - 1; i >= 0; i-- {
h = w.middleware[i](h)
}
if err := h(ctx); err != nil {
w.ErrorHandler(ctx, err)
return
}
}
}
func (w *Weavebox) writeLog(r *http.Request, start time.Time, status, size int) {
host, _, _ := net.SplitHostPort(r.Host)
username := "-"
if r.URL.User != nil {
if name := r.URL.User.Username(); name != "" {
username = name
}
}
fmt.Fprintf(w.Output, "%s - %s [%s] \"%s %s %s\" %d %d\n",
host,
username,
start.Format("02/Jan/2006:15:04:05 -0700"),
r.Method,
r.RequestURI,
r.Proto,
status,
size,
)
}
// Handler is a weavebox idiom for handling http.Requests
type Handler func(ctx *Context) error
// ErrorHandlerFunc is invoked when a Handler returns an error, and can be used
// to centralize error handling.
type ErrorHandlerFunc func(ctx *Context, err error)
// Context is required in each weavebox Handler and can be used to pass information
// between requests.
type Context struct {
// Context is a idiomatic way to pass information between requests.
// More information about context.Context can be found here:
// https://godoc.org/golang.org/x/net/context
Context context.Context
response http.ResponseWriter
request *http.Request
vars httprouter.Params
weavebox *Weavebox
}
// Response returns a default http.ResponseWriter
func (c *Context) Response() http.ResponseWriter {
return c.response
}
// Request returns a default http.Request ptr
func (c *Context) Request() *http.Request {
return c.request
}
// JSON is a helper function for writing a JSON encoded representation of v to
// the ResponseWriter.
func (c *Context) JSON(code int, v interface{}) error {
c.Response().Header().Set("Content-Type", "application/json")
c.Response().WriteHeader(code)
return json.NewEncoder(c.Response()).Encode(v)
}
// Text is a helper function for writing a text/plain string to the ResponseWriter
func (c *Context) Text(code int, text string) error {
c.Response().Header().Set("Content-Type", "text/plain")
c.Response().WriteHeader(code)
c.Response().Write([]byte(text))
return nil
}
// DecodeJSON is a helper that decodes the request Body to v.
// For a more in depth use of decoding and encoding JSON, use the std JSON package.
func (c *Context) DecodeJSON(v interface{}) error {
return json.NewDecoder(c.Request().Body).Decode(v)
}
// Render calls the templateEngines Render function
func (c *Context) Render(name string, data interface{}) error {
return c.weavebox.templateEngine.Render(c.Response(), name, data)
}
// Param returns the url named parameter given in the route prefix by its name
// app.Get("/:name", ..) => ctx.Param("name")
func (c *Context) Param(name string) string {
return c.vars.ByName(name)
}
// Query returns the url query parameter by its name.
// app.Get("/api?limit=25", ..) => ctx.Query("limit")
func (c *Context) Query(name string) string {
return c.request.URL.Query().Get(name)
}
// Form returns the form parameter by its name
func (c *Context) Form(name string) string {
return c.request.FormValue(name)
}
// Header returns the request header by name
func (c *Context) Header(name string) string {
return c.request.Header.Get(name)
}
// SetHeader set a header to the response. If the header allready exists the
// value will be overidden.
func (c *Context) SetHeader(key, value string) {
c.response.Header().Set(key, value)
}
// Redirect redirects the request to the provided URL with the given status code.
func (c *Context) Redirect(url string, code int) error {
if code < http.StatusMultipleChoices || code > http.StatusTemporaryRedirect {
return errors.New("invalid redirect code")
}
http.Redirect(c.response, c.request, url, code)
return nil
}
// Set can be used to store values in the context. Weavebox uses Google context
// for passing that value arround requests in a thread safe way.
func (c *Context) Set(key string, value interface{}) {
c.Context = context.WithValue(c.Context, key, value)
}
// Get retrieves the stored value from the context.
func (c *Context) Get(key string) interface{} {
return c.Context.Value(key)
}
type HTTPError struct {
Code int `json:"code"`
Description string `json:"description"`
}
// Error implements the error interface
func (e HTTPError) Error() string {
return e.Description
}
// HTTPError is helper function that constructs an error of type HTTPError.
// Returning HTTPErrors in handlers can be a verry productive way of handling
// errors in your handler and central errorHandler.
//
// func errorHandler(c *weavebox.Context, err error) {
// if httpErr, ok := err.(weavebox.HTTPError); ok {
// c.JSON(httpErr.Code, httpErr)
// }
// }
//
// This will give you always the correct statusCode passed in the handler and
// will also give you a nice JSON reponse.
func (c *Context) HTTPError(code int, desc string) HTTPError {
return HTTPError{
Code: code,
Description: desc,
}
}
// Log provides a structured logging tool based on go-kit's logger. Weavebox
// thinks structured logging is key in modern api's and webapps, its readable and
// eazy for machines to parse it.
// EG: c.Log("handler", "CreateUser", "input", User, "took", time.Since(start))
func (c *Context) Log(keyvals ...interface{}) {
c.weavebox.logger.Log(keyvals...)
}
type responseLogger struct {
w http.ResponseWriter
status int
size int
}
func (l *responseLogger) Write(p []byte) (int, error) {
if l.status == 0 {
l.status = http.StatusOK
}
size, err := l.w.Write(p)
l.size += size
return size, err
}
func (l *responseLogger) Header() http.Header {
return l.w.Header()
}
func (l *responseLogger) WriteHeader(code int) {
l.w.WriteHeader(code)
l.status = code
}
func (l *responseLogger) Status() int {
return l.status
}
func (l *responseLogger) Size() int {
return l.size
}
// Renderer renders any kind of template. Weavebox allows the use of different
// template engines, if they implement the Render method.
type Renderer interface {
Render(w io.Writer, name string, data interface{}) error
}