-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.go
57 lines (49 loc) · 1.46 KB
/
context.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
package kivikd
import (
"context"
"net/http"
"github.com/go-kivik/kivikd/v4/auth"
)
type contextKey struct {
name string
}
var (
// SessionKey is a context key used to access the authenticated session.
SessionKey = &contextKey{"session"}
// ClientContextKey is a context key used to access the kivik client.
ClientContextKey = &contextKey{"client"}
// ServiceContextKey is a context key used to access the serve.Service struct.
ServiceContextKey = &contextKey{"service"}
)
func setContext(s *Service) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ctx = context.WithValue(ctx, ClientContextKey, s.Client)
ctx = context.WithValue(ctx, ServiceContextKey, s)
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
})
}
}
// MustGetSession returns the user context for the currently authenticated user.
// If no session is set, the function panics.
func MustGetSession(ctx context.Context) *auth.Session {
s, ok := ctx.Value(SessionKey).(**auth.Session)
if !ok {
panic("No session!")
}
return *s
}
func mustGetSessionPtr(ctx context.Context) **auth.Session {
s, ok := ctx.Value(SessionKey).(**auth.Session)
if !ok {
panic("No session!")
}
return s
}
// GetService extracts the Kivik service from the request.
func GetService(r *http.Request) *Service {
service := r.Context().Value(ServiceContextKey).(*Service)
return service
}