Files
mtusi2026lab7/internal/transport/rest/requestid.go
T
Vladislav Kunetskiy 1b6e96ccc0
Application / Go invariants and static checks (pull_request) Canceled after 0s
Application / Lab7 verified TLS and retained features (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
lab7: безопасность, mTLS, OpenBao и PKI lifecycle
2026-11-10 14:39:57 +03:00

39 lines
815 B
Go

package rest
import (
"context"
"net/http"
"regexp"
"github.com/google/uuid"
)
const requestIDHeader = "X-Request-ID"
var requestIDPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,64}$`)
type requestIDKey struct{}
func requestIDFromContext(ctx context.Context) string {
id, _ := ctx.Value(requestIDKey{}).(string)
return id
}
func withRequestID(ctx context.Context, id string) context.Context {
return context.WithValue(ctx, requestIDKey{}, id)
}
func requestIDMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := r.Header.Get(requestIDHeader)
if !requestIDPattern.MatchString(id) {
id = uuid.NewString()
}
w.Header().Set(requestIDHeader, id)
next.ServeHTTP(w, r.WithContext(withRequestID(r.Context(), id)))
})
}