-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.go
More file actions
66 lines (56 loc) · 1.63 KB
/
Copy pathcontext.go
File metadata and controls
66 lines (56 loc) · 1.63 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
package rustygo
import (
"context"
"net/http"
)
type contextKey struct{}
var arenaContextKey = contextKey{}
// WithContextArena attaches an Arena to a context.
func WithContextArena(ctx context.Context, a *Arena) context.Context {
return context.WithValue(ctx, arenaContextKey, a)
}
// FromContext extracts an Arena from context.
func FromContext(ctx context.Context) (*Arena, bool) {
if ctx == nil {
return nil, false
}
a, ok := ctx.Value(arenaContextKey).(*Arena)
return a, ok
}
type scopeContextKey struct{}
var scopeKey = scopeContextKey{}
// WithContextScope attaches an active Scope to context and returns a cleanup function that exits the scope.
func WithContextScope(ctx context.Context, s *Scope) (context.Context, func()) {
ctx = context.WithValue(ctx, scopeKey, s)
cleanup := func() {
if s != nil && s.Active() {
s.Exit()
}
}
return ctx, cleanup
}
// ScopeFromContext extracts the active Scope from context.
func ScopeFromContext(ctx context.Context) (*Scope, bool) {
if ctx == nil {
return nil, false
}
s, ok := ctx.Value(scopeKey).(*Scope)
return s, ok
}
// HTTPMiddleware creates an HTTP middleware that binds an entered Scope to every request context
// and automatically exits the scope when the HTTP request finishes.
func HTTPMiddleware(a *Arena) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s := a.EnterScope()
defer func() {
if s.Active() {
s.Exit()
}
}()
ctx, _ := WithContextScope(r.Context(), s)
ctx = WithContextArena(ctx, a)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}