From 3f405de6a982866db1ed6adcbb23c7e4c3f05e8a Mon Sep 17 00:00:00 2001 From: Andy Hsu Date: Fri, 24 Nov 2023 19:17:37 +0800 Subject: [PATCH] feat: customize allow `origins`, `headers` and `methods` --- internal/conf/config.go | 12 ++++++++++++ server/router.go | 7 ++++--- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/internal/conf/config.go b/internal/conf/config.go index 2754064c..92761ea7 100644 --- a/internal/conf/config.go +++ b/internal/conf/config.go @@ -51,6 +51,12 @@ type TasksConfig struct { Copy TaskConfig `json:"copy" envPrefix:"COPY_"` } +type Cors struct { + AllowOrigins []string `json:"allow_origins" env:"ALLOW_ORIGINS"` + AllowMethods []string `json:"allow_methods" env:"ALLOW_METHODS"` + AllowHeaders []string `json:"allow_headers" env:"ALLOW_HEADERS"` +} + type Config struct { Force bool `json:"force" env:"FORCE"` SiteURL string `json:"site_url" env:"SITE_URL"` @@ -67,6 +73,7 @@ type Config struct { MaxConnections int `json:"max_connections" env:"MAX_CONNECTIONS"` TlsInsecureSkipVerify bool `json:"tls_insecure_skip_verify" env:"TLS_INSECURE_SKIP_VERIFY"` Tasks TasksConfig `json:"tasks" envPrefix:"TASKS_"` + Cors Cors `json:"cors" envPrefix:"CORS_"` } func DefaultConfig() *Config { @@ -120,5 +127,10 @@ func DefaultConfig() *Config { MaxRetry: 2, }, }, + Cors: Cors{ + AllowOrigins: []string{"*"}, + AllowMethods: []string{"*"}, + AllowHeaders: []string{"*"}, + }, } } diff --git a/server/router.go b/server/router.go index 7f179231..588cc071 100644 --- a/server/router.go +++ b/server/router.go @@ -163,8 +163,9 @@ func _fs(g *gin.RouterGroup) { func Cors(r *gin.Engine) { config := cors.DefaultConfig() - config.AllowAllOrigins = true - config.AllowHeaders = []string{"*"} - config.AllowMethods = []string{"*"} + //config.AllowAllOrigins = true + config.AllowOrigins = conf.Conf.Cors.AllowOrigins + config.AllowHeaders = conf.Conf.Cors.AllowHeaders + config.AllowMethods = conf.Conf.Cors.AllowMethods r.Use(cors.New(config)) }