Files
mtusi2026lab7/internal/transport/rest/requestid.go
T
Vladislav Kunetskiy 3d216fbd50 База lab7: контракт 1.7.0 и реализация lab1–lab6
Перенесены cmd/internal/config, compose.yaml, Dockerfile, скрипты, student-tests и evidence из mtusi-messenger (master, lab6). Skeleton lab7 (openapi/infrastructure 1.7.0, trust-matrix.md, security/THREAT_MODEL.md, infra/openbao, tests/security.py) сохранён; make test-security добавлен в Makefile.
2026-11-09 13:03:49 +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)))
})
}