pkg/rest/transport/request_id.go

31 lines
632 B
Go

package transport
import (
"math/rand/v2"
"net/http"
)
const charset = "abcdefghijklmnopqrstuvwxyz0123456789"
// genRequestID generates a random string of a given length.
func genRequestID() string {
b := make([]byte, 32)
for i := range b {
b[i] = charset[rand.IntN(len(charset))]
}
return string(b)
}
// RequestID ...
func RequestID(next http.RoundTripper) http.RoundTripper {
f := func(req *http.Request) (*http.Response, error) {
requestID := genRequestID()
ctx := req.Context()
req.Header.Set("X-Request-Id", requestID)
req = req.WithContext(ctx)
return next.RoundTrip(req)
}
return RoundTripFunc(f)
}