-
Notifications
You must be signed in to change notification settings - Fork 489
/
Copy pathmiddleware.go
70 lines (62 loc) · 2.16 KB
/
middleware.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
package correlation
import (
"context"
"github.com/gorilla/mux"
"net/http"
"net/url"
"time"
"github.com/edgexfoundry/go-mod-core-contracts/v3/clients/logger"
"github.com/edgexfoundry/go-mod-core-contracts/v3/common"
"github.com/edgexfoundry/go-mod-core-contracts/v3/models"
"github.com/google/uuid"
)
func ManageHeader(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
correlationID := r.Header.Get(common.CorrelationHeader)
if correlationID == "" {
correlationID = uuid.New().String()
}
// lint:ignore SA1029 legacy
// nolint:staticcheck // See golangci-lint #741
ctx := context.WithValue(r.Context(), common.CorrelationHeader, correlationID)
contentType := r.Header.Get(common.ContentType)
// lint:ignore SA1029 legacy
// nolint:staticcheck // See golangci-lint #741
ctx = context.WithValue(ctx, common.ContentType, contentType)
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
})
}
func LoggingMiddleware(lc logger.LoggingClient) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if lc.LogLevel() == models.TraceLog {
begin := time.Now()
correlationId := FromContext(r.Context())
lc.Trace("Begin request", common.CorrelationHeader, correlationId, "path", r.URL.Path)
next.ServeHTTP(w, r)
lc.Trace("Response complete", common.CorrelationHeader, correlationId, "duration", time.Since(begin).String())
} else {
next.ServeHTTP(w, r)
}
})
}
}
// UrlDecodeMiddleware decode the path variables
// After invoking the router.UseEncodedPath() func, the path variables needs to decode before passing to the controller
func UrlDecodeMiddleware(lc logger.LoggingClient) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
for k, v := range vars {
unescape, err := url.PathUnescape(v)
if err != nil {
lc.Debugf("failed to decode the %s from the value %s", k, v)
return
}
vars[k] = unescape
}
next.ServeHTTP(w, r)
})
}
}