diff --git a/trading_assistant_api/common/httpx/cors.go b/trading_assistant_api/common/httpx/cors.go index 80325f8..60601c8 100644 --- a/trading_assistant_api/common/httpx/cors.go +++ b/trading_assistant_api/common/httpx/cors.go @@ -7,7 +7,7 @@ func CORS() func(http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS") - w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With") + w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With, X-Request-ID") w.Header().Set("Access-Control-Max-Age", "86400") if r.Method == http.MethodOptions { w.WriteHeader(http.StatusNoContent) diff --git a/trading_assistant_api/common/httpx/request_id.go b/trading_assistant_api/common/httpx/request_id.go new file mode 100644 index 0000000..e7222bb --- /dev/null +++ b/trading_assistant_api/common/httpx/request_id.go @@ -0,0 +1,47 @@ +package httpx + +import ( + "context" + "crypto/rand" + "encoding/hex" + "net/http" + "strings" +) + +type reqIDKey struct{} + +func RequestID() func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + rid := incomingRID(r) + if rid == "" { + rid = genRID() + } + w.Header().Set("X-Request-ID", rid) + ctx := context.WithValue(r.Context(), reqIDKey{}, rid) + next.ServeHTTP(w, r.WithContext(ctx)) + }) + } +} + +func RequestIDFromContext(r *http.Request) string { + v := r.Context().Value(reqIDKey{}) + if s, ok := v.(string); ok { + return s + } + return "" +} + +func incomingRID(r *http.Request) string { + h := r.Header.Get("X-Request-ID") + if h == "" { + h = r.Header.Get("X-Request-Id") + } + return strings.TrimSpace(h) +} + +func genRID() string { + var b [16]byte + _, _ = rand.Read(b[:]) + return hex.EncodeToString(b[:]) +} diff --git a/trading_assistant_api/services/user/main.go b/trading_assistant_api/services/user/main.go index 13fea1c..b783302 100644 --- a/trading_assistant_api/services/user/main.go +++ b/trading_assistant_api/services/user/main.go @@ -66,7 +66,8 @@ func routes() http.Handler { svc := service.New(repo) h := handler.New(svc) cors := httpx.CORS() - return cors(router.New(h)) + reqID := httpx.RequestID() + return reqID(cors(router.New(h))) } func applySchema(path string) error {