forked from derekdowling/go-json-spec-handler
-
Notifications
You must be signed in to change notification settings - Fork 1
/
middleware.go
79 lines (68 loc) · 2.13 KB
/
middleware.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
/*
Package middleware contains utilities for Goji Middleware authors.
Unless you are writing middleware for your application, you should avoid
importing this package. Instead, use the abstractions provided by your
middleware package.
*/
package middleware
import (
"net/http"
"goji.io"
"goji.io/internal"
"golang.org/x/net/context"
)
/*
Pattern returns the most recently matched Pattern, or nil if no pattern was
matched.
*/
func Pattern(ctx context.Context) goji.Pattern {
p := ctx.Value(internal.Pattern)
if p == nil {
return nil
}
return p.(goji.Pattern)
}
/*
SetPattern returns a new context in which the given Pattern is used as the most
recently matched pattern.
*/
func SetPattern(ctx context.Context, p goji.Pattern) context.Context {
return context.WithValue(ctx, internal.Pattern, p)
}
/*
Handler returns the handler corresponding to the most recently matched Pattern,
or nil if no pattern was matched.
Internally, Goji converts net/http.Handlers into goji.Handlers using a wrapper
object. Users who wish to retrieve the original http.Handler they passed to Goji
may call UnwrapHandler.
The handler returned by this function is the one that will be dispatched to at
the end of the middleware stack. If the returned Handler is nil, http.NotFound
will be used instead.
*/
func Handler(ctx context.Context) goji.Handler {
h := ctx.Value(internal.Handler)
if h == nil {
return nil
}
return h.(goji.Handler)
}
/*
SetHandler returns a new context in which the given Handler was most recently
matched and which consequently will be dispatched to.
*/
func SetHandler(ctx context.Context, h goji.Handler) context.Context {
return context.WithValue(ctx, internal.Handler, h)
}
/*
UnwrapHandler extracts the original http.Handler from a Goji-wrapped Handler
object, or returns nil if the given Handler has not been wrapped in this way.
This function is necessary because Goji uses goji.Handler as its native data
type internally, and uses a wrapper struct to convert all http.Handlers it is
passed into goji.Handlers.
*/
func UnwrapHandler(h goji.Handler) http.Handler {
if cw, ok := h.(internal.ContextWrapper); ok {
return cw.Handler
}
return nil
}