...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package kivikd
16
17 import (
18 "context"
19 "net/http"
20
21 "github.com/go-kivik/kivik/v4/x/kivikd/auth"
22 )
23
24 type contextKey struct {
25 name string
26 }
27
28 var (
29
30 SessionKey = &contextKey{"session"}
31
32 ClientContextKey = &contextKey{"client"}
33
34 ServiceContextKey = &contextKey{"service"}
35 )
36
37 func setContext(s *Service) func(http.Handler) http.Handler {
38 return func(next http.Handler) http.Handler {
39 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
40 ctx := r.Context()
41 ctx = context.WithValue(ctx, ClientContextKey, s.Client)
42 ctx = context.WithValue(ctx, ServiceContextKey, s)
43 r = r.WithContext(ctx)
44 next.ServeHTTP(w, r)
45 })
46 }
47 }
48
49
50
51 func MustGetSession(ctx context.Context) *auth.Session {
52 s, ok := ctx.Value(SessionKey).(**auth.Session)
53 if !ok {
54 panic("No session!")
55 }
56 return *s
57 }
58
59 func mustGetSessionPtr(ctx context.Context) **auth.Session {
60 s, ok := ctx.Value(SessionKey).(**auth.Session)
61 if !ok {
62 panic("No session!")
63 }
64 return s
65 }
66
67
68 func GetService(r *http.Request) *Service {
69 service := r.Context().Value(ServiceContextKey).(*Service)
70 return service
71 }
72
View as plain text