diff options
Diffstat (limited to 'middleware/request_id.go')
-rw-r--r-- | middleware/request_id.go | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/middleware/request_id.go b/middleware/request_id.go new file mode 100644 index 0000000..016b44a --- /dev/null +++ b/middleware/request_id.go @@ -0,0 +1,35 @@ +package middleware + +import ( + "context" + "net/http" + + "go.neonxp.ru/objectid" +) + +const RequestIDHeader string = "X-Request-ID" + +func RequestID(next http.Handler) http.Handler { + objectid.Seed() + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requestID := r.Header.Get(RequestIDHeader) + if requestID == "" { + requestID = objectid.New().String() + } + + next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), requestIDKey, requestID))) + }) +} + +func GetRequestID(r *http.Request) string { + rid := r.Context().Value(requestIDKey) + if rid == nil { + return "" + } + srid, ok := rid.(string) + if !ok { + return "" + } + + return srid +} |