/
context.go
86 lines (64 loc) · 2.18 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
77
78
79
80
81
82
83
84
85
86
package hecho
import (
"github.com/kamva/hexa"
"github.com/kamva/tracer"
"github.com/labstack/echo/v4"
)
// NewCtx get hexa Context and return itself context.
type CtxCreator func(ctx hexa.Context) hexa.Context
const (
// ContextKeyHexaRequestID uses as key in context to store request id to use in context middleware
ContextKeyHexaRequestID = "__hexa_ctx.rid__"
// ContextKeyHexaCorrelationID uses as key in context to store correlation id to use in context middleware
ContextKeyHexaCorrelationID = "__hexa_ctx.cid__"
// ContextKeyHexaCtx is the identifier to set the hexa context as a field in the context of a request.
ContextKeyHexaCtx = "__hexa_ctx.ctx__"
// ContextKeyHexaUser is the identifier to set the hexa user as a field in the context of a request.
ContextKeyHexaUser = "__hexa_ctx.user__"
)
// This is default implementation of context creator.
func DefaultCtxCreator(ctx hexa.Context) hexa.Context {
return ctx
}
// getHexaUser returns hexa user instance from the current user.
func getHexaUser(ctx echo.Context) (hexa.User, hexa.Error) {
// Get user if exists:
u := ctx.Get(ContextKeyHexaUser)
if u == nil {
return nil, errUserNotFound
}
if u, ok := u.(hexa.User); ok {
return u, nil
} else {
return nil, errContextUserNotImplementedHexaUser
}
}
// getCorrelationID returns the request correlation id.
func getCorrelationID(ctx echo.Context) (string, hexa.Error) {
// Get Request ID if exists:
cid := ctx.Get(ContextKeyHexaCorrelationID).(string)
if cid == "" {
return "", errCorrelationIDNotFound
}
return cid, nil
}
// HexaContext set hexa context on each request.
func HexaContext(ctxCreator CtxCreator, logger hexa.Logger, translator hexa.Translator) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(ctx echo.Context) error {
req := ctx.Request()
user, err := getHexaUser(ctx)
if err != nil {
return tracer.Trace(err)
}
cid, err := getCorrelationID(ctx)
if err != nil {
return tracer.Trace(err)
}
al := req.Header.Get("Accept-Language")
// Set context
ctx.Set(ContextKeyHexaCtx, ctxCreator(hexa.NewCtx(ctx.Request(), cid, al, user, logger, translator)))
return next(ctx)
}
}
}