Sfoglia il codice sorgente

feat: allowed origins environment variable

Fela Maslen 5 anni fa
parent
commit
6e8fd1e3c1

+ 11 - 0
gmus-backend/pkg/config/config.go

@@ -7,6 +7,7 @@ import (
 	"os"
 	"path/filepath"
 	"strconv"
+	"strings"
 
 	"github.com/joho/godotenv"
 
@@ -129,6 +130,15 @@ func getRedisUrl() string {
 	return url
 }
 
+func getAllowedOrigins() []string {
+  origins, hasOrigins := os.LookupEnv("ALLOWED_ORIGINS")
+  if !hasOrigins {
+    return []string{"*"}
+  }
+
+  return strings.Split(origins, ",")
+}
+
 type config struct {
 	DatabaseUrl      string
 	LogLevel         logger.LogLevel
@@ -136,4 +146,5 @@ type config struct {
 	Host             string
 	Port             int
 	RedisUrl         string
+  AllowedOrigins []string
 }

+ 1 - 0
gmus-backend/pkg/config/main.go

@@ -14,5 +14,6 @@ func GetConfig() config {
 		Host:             getListenHost(),
 		Port:             getPort(),
 		RedisUrl:         getRedisUrl(),
+    AllowedOrigins: getAllowedOrigins(),
 	}
 }

+ 4 - 1
gmus-backend/pkg/server/server.go

@@ -39,7 +39,10 @@ func StartServer() {
 
 	port := conf.Port
 
-	handler := cors.AllowAll().Handler(router)
+	handler := cors.New(cors.Options{
+    AllowedOrigins: conf.AllowedOrigins,
+    AllowCredentials: true,
+  }).Handler(router)
 
 	l.Info("Starting server on %s:%d\n", conf.Host, port)
 	log.Fatal(http.ListenAndServe(fmt.Sprintf("%s:%d", conf.Host, port), handler))