requestid.go60 lines, 1.8 KB
| 1 | package httpx |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/rand" |
| 6 | "log/slog" |
| 7 | "net/http" |
| 8 | |
| 9 | "github.com/fiston-user/payments/internal/platform/logging" |
| 10 | ) |
| 11 | |
| 12 | // RequestIDHeader carries a request's ID between services, and back to clients. |
| 13 | const RequestIDHeader = "X-Request-ID" |
| 14 | |
| 15 | type requestIDKey struct{} |
| 16 | |
| 17 | // RequestID gives every request an ID. It keeps a valid ID sent by the caller, |
| 18 | // so one ID can follow a request across services, and makes a new one |
| 19 | // otherwise. The ID goes into the context, onto every log line, and back to |
| 20 | // the client in the response header. |
| 21 | func RequestID(next http.Handler) http.Handler { |
| 22 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 23 | ctx, id := WithRequestID(r.Context(), r.Header.Get(RequestIDHeader)) |
| 24 | w.Header().Set(RequestIDHeader, id) |
| 25 | next.ServeHTTP(w, r.WithContext(ctx)) |
| 26 | }) |
| 27 | } |
| 28 | |
| 29 | // WithRequestID returns a copy of ctx that carries a request ID, and the ID: |
| 30 | // id if it's valid, or a new one. Other transports, like gRPC, use it too, so |
| 31 | // a request keeps its ID wherever it goes. |
| 32 | func WithRequestID(ctx context.Context, id string) (context.Context, string) { |
| 33 | if !validRequestID(id) { |
| 34 | id = rand.Text() |
| 35 | } |
| 36 | ctx = context.WithValue(ctx, requestIDKey{}, id) |
| 37 | return logging.With(ctx, slog.String("request_id", id)), id |
| 38 | } |
| 39 | |
| 40 | // RequestIDFrom returns the ID of the request that ctx belongs to, or "". |
| 41 | func RequestIDFrom(ctx context.Context) string { |
| 42 | id, _ := ctx.Value(requestIDKey{}).(string) |
| 43 | return id |
| 44 | } |
| 45 | |
| 46 | // validRequestID accepts up to 64 letters, digits, dashes and underscores. The |
| 47 | // header comes from the client, and we copy it into our logs and responses. |
| 48 | func validRequestID(id string) bool { |
| 49 | if id == "" || len(id) > 64 { |
| 50 | return false |
| 51 | } |
| 52 | for _, c := range id { |
| 53 | switch { |
| 54 | case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9', c == '-', c == '_': |
| 55 | default: |
| 56 | return false |
| 57 | } |
| 58 | } |
| 59 | return true |
| 60 | } |