-
-
Notifications
You must be signed in to change notification settings - Fork 36
/
globalmux_old.go
89 lines (78 loc) · 2.43 KB
/
globalmux_old.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
// +build !go1.7
package kami
import (
"net/http"
"github.com/dimfeld/httptreemux"
"github.com/zenazn/goji/web/mutil"
"golang.org/x/net/context"
)
var (
// Context is the root "god object" from which every request's context will derive.
Context = context.Background()
// Cancel will, if true, automatically cancel the context of incoming requests after they finish.
Cancel bool
// PanicHandler will, if set, be called on panics.
// You can use kami.Exception(ctx) within the panic handler to get panic details.
PanicHandler HandlerType
// LogHandler will, if set, wrap every request and be called at the very end.
LogHandler func(context.Context, mutil.WriterProxy, *http.Request)
)
// NotFound registers a special handler for unregistered (404) paths.
// If handle is nil, use the default http.NotFound behavior.
func NotFound(handler HandlerType) {
// set up the default handler if needed
// we need to bless this so middleware will still run for a 404 request
if handler == nil {
handler = HandlerFunc(func(_ context.Context, w http.ResponseWriter, r *http.Request) {
http.NotFound(w, r)
})
}
h := bless(wrap(handler))
routes.NotFoundHandler = func(w http.ResponseWriter, r *http.Request) {
h(w, r, nil)
}
}
// MethodNotAllowed registers a special handler for automatically responding
// to invalid method requests (405).
func MethodNotAllowed(handler HandlerType) {
if handler == nil {
handler = HandlerFunc(func(_ context.Context, w http.ResponseWriter, r *http.Request) {
http.Error(w,
http.StatusText(http.StatusMethodNotAllowed),
http.StatusMethodNotAllowed,
)
})
}
h := bless(wrap(handler))
routes.MethodNotAllowedHandler = func(w http.ResponseWriter, r *http.Request, methods map[string]httptreemux.HandlerFunc) {
if !enable405 {
routes.NotFoundHandler(w, r)
return
}
h(w, r, nil)
}
}
// bless creates a new kamified handler using the global mux and middleware.
func bless(h ContextHandler) httptreemux.HandlerFunc {
k := kami{
handler: h,
base: &Context,
autocancel: &Cancel,
middleware: defaultMW,
panicHandler: &PanicHandler,
logHandler: &LogHandler,
}
return k.handle
}
// Reset changes the root Context to context.Background().
// It removes every handler and all middleware.
func Reset() {
Context = context.Background()
Cancel = false
PanicHandler = nil
LogHandler = nil
defaultMW = newWares()
routes = newRouter()
NotFound(nil)
MethodNotAllowed(nil)
}