From 92ddff09179626fe485078385bcb2b46d119aeed Mon Sep 17 00:00:00 2001 From: William P Date: Wed, 3 Jun 2026 00:59:28 +0000 Subject: [PATCH] server: implement CORS --- server/api/api.go | 12 ++++++++++++ server/go.mod | 1 + server/go.sum | 2 ++ server/main.go | 2 +- 4 files changed, 16 insertions(+), 1 deletion(-) diff --git a/server/api/api.go b/server/api/api.go index 7b4aeb4..0a418da 100644 --- a/server/api/api.go +++ b/server/api/api.go @@ -3,9 +3,12 @@ package api import ( "context" "net/http" + "os" + "strings" "git.dubyatp.xyz/dubyatp/scannerbot/server/db" "github.com/go-chi/chi/v5" + "github.com/go-chi/cors" ) func Start() { @@ -17,6 +20,15 @@ func Start() { r := chi.NewRouter() + r.Use(cors.Handler(cors.Options{ + AllowedOrigins: strings.Split(os.Getenv("ALLOWED_ORIGINS"), ","), + AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, + AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"}, + ExposedHeaders: []string{"Link"}, + AllowCredentials: true, + MaxAge: 300, // preflight request cache + })) + r.Get("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hello world")) }) diff --git a/server/go.mod b/server/go.mod index c4fc809..8956cf0 100644 --- a/server/go.mod +++ b/server/go.mod @@ -14,6 +14,7 @@ require ( require ( github.com/ajg/form v1.5.1 // indirect + github.com/go-chi/cors v1.2.2 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect diff --git a/server/go.sum b/server/go.sum index c675da7..58ad229 100644 --- a/server/go.sum +++ b/server/go.sum @@ -5,6 +5,8 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/go-chi/chi/v5 v5.2.5 h1:Eg4myHZBjyvJmAFjFvWgrqDTXFyOzjj7YIm3L3mu6Ug= github.com/go-chi/chi/v5 v5.2.5/go.mod h1:X7Gx4mteadT3eDOMTsXzmI4/rwUpOwBHLpAfupzFJP0= +github.com/go-chi/cors v1.2.2 h1:Jmey33TE+b+rB7fT8MUy1u0I4L+NARQlK6LhzKPSyQE= +github.com/go-chi/cors v1.2.2/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58= github.com/go-chi/render v1.0.3 h1:AsXqd2a1/INaIfUSKq3G5uA8weYx20FOsM7uSoCyyt4= github.com/go-chi/render v1.0.3/go.mod h1:/gr3hVkmYR0YlEy3LxCuVRFzEu9Ruok+gFqbIofjao0= github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY= diff --git a/server/main.go b/server/main.go index f4e9dd5..c9b3910 100644 --- a/server/main.go +++ b/server/main.go @@ -10,7 +10,7 @@ import ( ) var REQUIRED_ENVS = [...]string{ - "DATABASE_URL", "JWT_SECRET", "FILE_BACKEND", + "DATABASE_URL", "JWT_SECRET", "FILE_BACKEND", "ALLOWED_ORIGINS", } func checkEnvVars(keys []string) (bool, []string) {