-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrequest_id.go
More file actions
36 lines (30 loc) · 980 Bytes
/
request_id.go
File metadata and controls
36 lines (30 loc) · 980 Bytes
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
package middleware
import (
"context"
"net/http"
"github.com/gofrs/uuid"
)
const requestIDHeader = "X-Request-Id"
// requestIDKey is a private unique key that is used for request ID in the context.
type requestIDKey struct{ kind string }
// RequestID is a middleware that injects a request ID into the context of each
// request. A request ID is a string (randomly generated UUID).
func RequestID(next http.Handler) http.Handler {
return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
requestID := r.Header.Get(requestIDHeader)
if requestID == "" {
requestUUID, _ := uuid.NewV4()
requestID = requestUUID.String()
}
next.ServeHTTP(w, r.WithContext(
context.WithValue(r.Context(), requestIDKey{}, requestID)),
)
},
)
}
// RequestIDFromContext pulls request ID from the context or empty string.
func RequestIDFromContext(ctx context.Context) string {
requestID, _ := ctx.Value(requestIDKey{}).(string)
return requestID
}