-
Notifications
You must be signed in to change notification settings - Fork 279
/
middleware.go
53 lines (46 loc) · 1.55 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
package sessions
import (
"context"
"net/http"
)
// Context keys
var (
SessionCtxKey = &contextKey{"Session"}
ErrorCtxKey = &contextKey{"Error"}
)
// RetrieveSession takes a slice of session loaders and tries to find a valid
// session in the order they were supplied and is added to the request's context
func RetrieveSession(s SessionLoader) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return retrieve(s)(next)
}
}
func retrieve(s SessionLoader) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
hfn := func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
jwt, err := s.LoadSession(r)
ctx = NewContext(ctx, jwt, err)
next.ServeHTTP(w, r.WithContext(ctx))
}
return http.HandlerFunc(hfn)
}
}
// NewContext sets context values for the user session state and error.
func NewContext(ctx context.Context, jwt string, err error) context.Context {
ctx = context.WithValue(ctx, SessionCtxKey, jwt)
ctx = context.WithValue(ctx, ErrorCtxKey, err)
return ctx
}
// FromContext retrieves context values for the user session state and error.
func FromContext(ctx context.Context) (string, error) {
jwt, _ := ctx.Value(SessionCtxKey).(string)
err, _ := ctx.Value(ErrorCtxKey).(error)
return jwt, err
}
// contextKey is a value for use with context.WithValue. It's used as
// a pointer so it fits in an interface{} without allocation. This technique
// for defining context keys was copied from Go 1.7's new use of context in net/http.
type contextKey struct {
name string
}