Skip to content

Commit b794a49

Browse files
committed
backend: fix cors
1 parent f716804 commit b794a49

1 file changed

Lines changed: 19 additions & 6 deletions

File tree

backend/cmd/offi/serve.go

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -61,22 +61,24 @@ func serveAction(ctx context.Context, _ *cli.Command) error {
6161
return fmt.Errorf("failed to init database client: %w", err)
6262
}
6363

64+
corsHandler := cors.New(cors.Options{
65+
AllowedOrigins: []string{"https://logs.tf", "https://etf2l.org", "https://steamcommunity.com"},
66+
AllowedMethods: []string{http.MethodGet},
67+
AllowedHeaders: []string{"Content-Type", "X-Offi-Version"},
68+
})
69+
6470
srv := service.NewService(cacheClient, dbClient, etf2lClient, logsClient)
6571

66-
handler, err := gen.NewServer(srv)
72+
handler, err := gen.NewServer(srv, gen.WithMethodNotAllowed(notAllowedWithCORS(corsHandler)))
6773
if err != nil {
6874
return fmt.Errorf("failed to init api server: %w", err)
6975
}
7076

7177
router := chi.NewRouter()
7278

73-
router.Use(cors.Handler(cors.Options{
74-
AllowedOrigins: []string{"https://logs.tf", "https://etf2l.org", "https://steamcommunity.com"},
75-
AllowedMethods: []string{http.MethodGet},
76-
AllowedHeaders: []string{"X-Offi-Version"},
77-
}))
7879
router.Use(middleware.Recoverer)
7980
router.Use(middleware.RealIP)
81+
router.Use(corsHandler.Handler)
8082
router.Use(tracing.NewMiddleware(handler))
8183
router.Use(tracing.InjectTracing)
8284

@@ -109,3 +111,14 @@ func serveAction(ctx context.Context, _ *cli.Command) error {
109111

110112
return nil
111113
}
114+
115+
func notAllowedWithCORS(handler *cors.Cors) func(w http.ResponseWriter, r *http.Request, allowed string) {
116+
return func(w http.ResponseWriter, r *http.Request, allowed string) {
117+
if r.Method == http.MethodOptions {
118+
handler.Handler(http.NotFoundHandler()).ServeHTTP(w, r)
119+
} else {
120+
w.Header().Set("Allow", allowed)
121+
w.WriteHeader(http.StatusMethodNotAllowed)
122+
}
123+
}
124+
}

0 commit comments

Comments
 (0)