-
Notifications
You must be signed in to change notification settings - Fork 28
/
context.go
65 lines (53 loc) · 1.43 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
58
59
60
61
62
63
64
65
// SPDX-License-Identifier: Apache-2.0
package compiler
import (
"context"
"github.com/gin-gonic/gin"
)
// key defines the key type for storing
// the compiler Engine in the context.
const key = "compiler"
// FromContext retrieves the compiler Engine from the context.Context.
func FromContext(c context.Context) Engine {
// get compiler value from context.Context
v := c.Value(key)
if v == nil {
return nil
}
// cast compiler value to expected Engine type
e, ok := v.(Engine)
if !ok {
return nil
}
return e
}
// FromGinContext retrieves the compiler Engine from the gin.Context.
func FromGinContext(c *gin.Context) Engine {
// get compiler value from gin.Context
//
// https://pkg.go.dev/github.com/gin-gonic/gin?tab=doc#Context.Get
v, ok := c.Get(key)
if !ok {
return nil
}
// cast compiler value to expected Engine type
e, ok := v.(Engine)
if !ok {
return nil
}
return e
}
// WithContext inserts the compiler Engine into the context.Context.
func WithContext(c context.Context, e Engine) context.Context {
// set the compiler Engine in the context.Context
//
//nolint:revive,staticcheck // ignore using string with context value
return context.WithValue(c, key, e)
}
// WithGinContext inserts the compiler Engine into the gin.Context.
func WithGinContext(c *gin.Context, e Engine) {
// set the compiler Engine in the gin.Context
//
// https://pkg.go.dev/github.com/gin-gonic/gin?tab=doc#Context.Set
c.Set(key, e)
}