diff --git a/trading_assistant_api/common/httpx/cors.go b/trading_assistant_api/common/httpx/cors.go new file mode 100644 index 0000000..80325f8 --- /dev/null +++ b/trading_assistant_api/common/httpx/cors.go @@ -0,0 +1,19 @@ +package httpx + +import "net/http" + +func CORS() func(http.Handler) http.Handler { + return func(next 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-Max-Age", "86400") + if r.Method == http.MethodOptions { + w.WriteHeader(http.StatusNoContent) + return + } + next.ServeHTTP(w, r) + }) + } +} diff --git a/trading_assistant_api/services/user/internal/handler/user_handler.go b/trading_assistant_api/services/user/internal/handler/user_handler.go index 7291505..11bc1a0 100644 --- a/trading_assistant_api/services/user/internal/handler/user_handler.go +++ b/trading_assistant_api/services/user/internal/handler/user_handler.go @@ -69,13 +69,25 @@ func (h *Handler) Login(w http.ResponseWriter, r *http.Request) { } func (h *Handler) Healthz(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + httpx.MethodNotAllowed(w, string(codes.MethodNotAllowed)) + return + } httpx.OK(w, nil) } func (h *Handler) Version(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + httpx.MethodNotAllowed(w, string(codes.MethodNotAllowed)) + return + } httpx.OK(w, map[string]string{"version": "user-service v0.1.0"}) } func (h *Handler) Root(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + httpx.MethodNotAllowed(w, string(codes.MethodNotAllowed)) + return + } httpx.OK(w, map[string]string{"service": "user"}) } diff --git a/trading_assistant_api/services/user/main.go b/trading_assistant_api/services/user/main.go index 5e58a2d..13fea1c 100644 --- a/trading_assistant_api/services/user/main.go +++ b/trading_assistant_api/services/user/main.go @@ -12,6 +12,7 @@ import ( "common/db" "common/logger" "common/utils" + "common/httpx" "user/internal/handler" "user/internal/repository" "user/internal/router" @@ -64,7 +65,8 @@ func routes() http.Handler { repo := repository.New(pg) svc := service.New(repo) h := handler.New(svc) - return router.New(h) + cors := httpx.CORS() + return cors(router.New(h)) } func applySchema(path string) error {