diff options
author | Alexander NeonXP Kiryukhin <i@neonxp.ru> | 2024-04-06 20:05:14 +0300 |
---|---|---|
committer | Alexander NeonXP Kiryukhin <i@neonxp.ru> | 2024-04-06 20:05:14 +0300 |
commit | e2509238d2b7566492e3f0a6b71563277487c98e (patch) | |
tree | 191a14e7849071d6603389af4e80a2c7840d8e2d /request_id.go |
initial
Diffstat (limited to 'request_id.go')
-rw-r--r-- | request_id.go | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/request_id.go b/request_id.go new file mode 100644 index 0000000..67a0c82 --- /dev/null +++ b/request_id.go @@ -0,0 +1,39 @@ +package middleware + +import ( + "context" + "net/http" + + "github.com/google/uuid" +) + +type ctxKeyRequestID int + +const ( + RequestIDKey ctxKeyRequestID = 0 + RequestIDHeader string = "X-Request-ID" +) + +func RequestID(handler http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requestID := r.Header.Get(RequestIDHeader) + if requestID == "" { + requestID = uuid.NewString() + } + + handler.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 +} |