-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcontext_additional_fields.go
More file actions
60 lines (46 loc) · 1.64 KB
/
context_additional_fields.go
File metadata and controls
60 lines (46 loc) · 1.64 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
package limen
import (
"context"
"net/http"
)
type contextKeyAdditionalFields struct{}
type AdditionalFieldsFunc func(ctx *AdditionalFieldsContext) (map[string]any, error)
type AdditionalFieldsContext struct {
request *http.Request
response http.ResponseWriter
body map[string]any
}
func newAdditionalFieldsContext(request *http.Request, response http.ResponseWriter) *AdditionalFieldsContext {
ctx := &AdditionalFieldsContext{
request: request,
response: response,
body: GetJSONBody(request),
}
return ctx
}
func (ctx *AdditionalFieldsContext) GetBody() map[string]any {
return ctx.body
}
func (ctx *AdditionalFieldsContext) GetBodyValue(key string) any {
return ctx.body[key]
}
func (ctx *AdditionalFieldsContext) GetHeader(key string) string {
return ctx.request.Header.Get(key)
}
func (ctx *AdditionalFieldsContext) GetHeaders() http.Header {
return ctx.request.Header
}
func (ctx *AdditionalFieldsContext) IsEmpty(key string) bool {
return ctx.body[key] == nil || ctx.body[key] == ""
}
func withAdditionalFieldsContext(ctx context.Context, r *http.Request, w http.ResponseWriter) context.Context {
return context.WithValue(ctx, contextKeyAdditionalFields{}, newAdditionalFieldsContext(r, w))
}
// getAdditionalFieldsContext retrieves the AdditionalFieldsContext from the req context.
// Returns an empty context (with nil request/response) if not in HTTP context (e.g., background jobs, CLI).
func getAdditionalFieldsContext(ctx context.Context) *AdditionalFieldsContext {
if afCtx, ok := ctx.Value(contextKeyAdditionalFields{}).(*AdditionalFieldsContext); ok {
return afCtx
}
return newAdditionalFieldsContext(nil, nil)
}