~bigbes/huntsman

huntsman/internal/server/middleware/requestid.go -rw-r--r-- 996 bytes
766fa805 — Eugene Blikh Add BSD 2-Clause license 6 days ago
                                                                                
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 contains chi-compatible HTTP middleware for the server.
package middleware

import (
	"context"
	"net/http"

	"github.com/google/uuid"
)

type ctxKey string

// RequestIDKey is the context key under which the request ID is stored.
const RequestIDKey ctxKey = "request_id"

// RequestID propagates an X-Request-ID header through the request, generating
// a UUID when the client didn't send one. The header is always echoed back.
func RequestID(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		id := r.Header.Get("X-Request-ID")
		if id == "" {
			id = uuid.NewString()
		}
		ctx := context.WithValue(r.Context(), RequestIDKey, id)
		w.Header().Set("X-Request-ID", id)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}

// GetRequestID returns the request ID stored in ctx, or "" if absent.
func GetRequestID(ctx context.Context) string {
	if id, ok := ctx.Value(RequestIDKey).(string); ok {
		return id
	}
	return ""
}