forked from cloudtrust/common-service
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcorrelation.go
43 lines (34 loc) · 1.45 KB
/
correlation.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
package middleware
import (
"context"
"net/http"
"regexp"
cs "github.com/cloudtrust/common-service/v2"
errorhandler "github.com/cloudtrust/common-service/v2/errors"
gen "github.com/cloudtrust/common-service/v2/idgenerator"
"github.com/cloudtrust/common-service/v2/log"
"github.com/cloudtrust/common-service/v2/tracing"
)
const (
regExpCorrelationID = `^[\w\d_#@-]{1,100}$`
hdrCorrelationID = "X-Correlation-ID"
)
// MakeHTTPCorrelationIDMW retrieve the correlation ID from the HTTP header 'X-Correlation-ID'.
// It there is no such header, it generates a correlation ID.
func MakeHTTPCorrelationIDMW(idGenerator gen.IDGenerator, _ tracing.OpentracingClient, _ log.Logger, componentName, componentID string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
var correlationID = req.Header.Get(hdrCorrelationID)
if correlationID == "" {
correlationID = idGenerator.NextID()
} else if match, _ := regexp.MatchString(regExpCorrelationID, correlationID); !match {
httpErrorHandler(req.Context(), http.StatusBadRequest, errorhandler.CreateInvalidQueryParameterError(hdrCorrelationID), w)
return
}
var ctx = context.WithValue(req.Context(), cs.CtContextCorrelationID, correlationID)
// Set X-Correlation-ID header for future response
w.Header().Set(hdrCorrelationID, correlationID)
next.ServeHTTP(w, req.WithContext(ctx))
})
}
}