-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.go
More file actions
77 lines (67 loc) · 1.97 KB
/
Copy pathcontext.go
File metadata and controls
77 lines (67 loc) · 1.97 KB
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
package gimlet
import (
"context"
"github.com/gin-gonic/gin"
)
// ContextKey is used to define keys for all gimlet context values so that keys can be
// shared across packages without collisions.
type ContextKey uint8
const (
KeyUnknown ContextKey = iota
KeyRequestID
KeyUserClaims
KeyAccessToken
KeyCacheControl
KeyCacheHandler
KeyRefreshToken
KeyAuthenticationSource
)
var contextKeyNames = [8]string{
"unknown",
"requestID",
"userClaims",
"accessToken",
"cacheControl",
"cacheHandler",
"refreshToken",
"authenticationSource",
}
func (c ContextKey) String() string {
if int(c) < len(contextKeyNames) {
return contextKeyNames[c]
}
return contextKeyNames[0]
}
// Sets a value in the gin context using a gimlet context key.
func Set(c *gin.Context, key ContextKey, value any) {
c.Set(key.String(), value)
}
// Gets a value from the gin context using a gimlet context key; if the key does not
// exist, it checks the request context for the value. If a context is passed in, it
// will retrieve the value from the request context instead of the gin context.
func Get(c any, key ContextKey) (any, bool) {
switch ctx := c.(type) {
case *gin.Context:
// If c is a gin.Context, first try to get the value from the gin
if value, exists := ctx.Get(key.String()); exists {
return value, true
}
return Get(ctx.Request.Context(), key)
case context.Context:
value := ctx.Value(key)
return value, value != nil
default:
return nil, false
}
}
// SetContext updates the request context with a new value for the specified key.
func SetContext(c *gin.Context, key ContextKey, value any) {
// HACK: this creates a shallow copy of the request, which might cause issues?
ctx := context.WithValue(c.Request.Context(), key, value)
c.Request = c.Request.WithContext(ctx)
}
// SetBoth updates both the gin context and the request context with a new value for the specified key.
func SetBoth(c *gin.Context, key ContextKey, value any) {
Set(c, key, value)
SetContext(c, key, value)
}