tsweb: expose function to generate request IDs

For use in corp.

Updates tailscale/corp#2549

Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
Change-Id: I71debae1ce9ae48cf69cc44c2ab5c443fc3b2005
pull/11275/head
Andrew Dunham 9 months ago
parent 7912d76da0
commit 23e9447871

@ -33,20 +33,27 @@ var RequestIDKey ctxkey.Key[RequestID]
// or generate a new one. // or generate a new one.
const RequestIDHeader = "X-Tailscale-Request-Id" const RequestIDHeader = "X-Tailscale-Request-Id"
// GenerateRequestID generates a new request ID with the current format.
func GenerateRequestID() RequestID {
// REQ-1 indicates the version of the RequestID pattern. It is
// currently arbitrary but allows for forward compatible
// transitions if needed.
return RequestID("REQ-1" + uuid.NewString())
}
// SetRequestID is an HTTP middleware that injects a RequestID in the // SetRequestID is an HTTP middleware that injects a RequestID in the
// *http.Request Context. The value of that request id is either retrieved from // *http.Request Context. The value of that request id is either retrieved from
// the RequestIDHeader or a randomly generated one if not exists. Inner // the RequestIDHeader or a randomly generated one if not exists. Inner
// handlers can retrieve this ID from the RequestIDFromContext function. // handlers can retrieve this ID from the RequestIDFromContext function.
func SetRequestID(h http.Handler) http.Handler { func SetRequestID(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := r.Header.Get(RequestIDHeader) var rid RequestID
if id == "" { if id := r.Header.Get(RequestIDHeader); id != "" {
// REQ-1 indicates the version of the RequestID pattern. It is rid = RequestID(id)
// currently arbitrary but allows for forward compatible } else {
// transitions if needed. rid = GenerateRequestID()
id = "REQ-1" + uuid.NewString()
} }
ctx := RequestIDKey.WithValue(r.Context(), RequestID(id)) ctx := RequestIDKey.WithValue(r.Context(), rid)
r = r.WithContext(ctx) r = r.WithContext(ctx)
h.ServeHTTP(w, r) h.ServeHTTP(w, r)
}) })

Loading…
Cancel
Save