-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.go
76 lines (64 loc) · 2.06 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
66
67
68
69
70
71
72
73
74
75
76
// Copyright (c) 2022, Roel Schut. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package serv
import (
"context"
"net/http"
)
type ctxValuesKey struct{}
type ctxValues struct {
serverName string
handlerName string
}
// ServerName gets the server's name from context values. Its return value may
// be an empty string.
func ServerName(ctx context.Context) string {
if v := ctx.Value(ctxValuesKey{}); v != nil {
return v.(*ctxValues).serverName
}
return ""
}
// AddServerName adds the server's name to the request's context. This is done
// automatically when a name is set using [WithName].
// The server's name can be retrieved using [ServerName].
func AddServerName(name string, next http.Handler) http.Handler {
return http.HandlerFunc(func(wri http.ResponseWriter, req *http.Request) {
ctx, settings, exists := withCtxValues(req.Context())
settings.serverName = name
if !exists {
// add new context to request
req = req.WithContext(ctx)
}
next.ServeHTTP(wri, req)
})
}
// HandlerName gets the handler's name from the context values. Its returned
// value may be an empty string.
func HandlerName(ctx context.Context) string {
if v := ctx.Value(ctxValuesKey{}); v != nil {
return v.(*ctxValues).handlerName
}
return ""
}
// AddHandlerName adds name as value to the request's context. It should
// be used on a per route/handler basis.
// The handler's name can be retrieved using [HandlerName].
func AddHandlerName(name string, next http.Handler) http.Handler {
return http.HandlerFunc(func(wri http.ResponseWriter, req *http.Request) {
ctx, settings, exists := withCtxValues(req.Context())
settings.handlerName = name
if !exists {
// add new context to request
req = req.WithContext(ctx)
}
next.ServeHTTP(wri, req)
})
}
func withCtxValues(ctx context.Context) (context.Context, *ctxValues, bool) {
if v := ctx.Value(ctxValuesKey{}); v != nil {
return ctx, v.(*ctxValues), true
}
v := new(ctxValues)
return context.WithValue(ctx, ctxValuesKey{}, v), v, false
}