feat: implement CORS support with configurable allowed origins

This commit is contained in:
mlogclub
2026-05-27 22:05:02 +08:00
parent 5bf4935a1f
commit 4d816182ee
6 changed files with 158 additions and 7 deletions
+8 -1
View File
@@ -30,7 +30,8 @@ type WxWorkNotifyConfig struct {
}
type ServerConfig struct {
Port int `yaml:"port"`
Port int `yaml:"port"`
CORS CORSConfig `yaml:"cors"`
}
func (s ServerConfig) Address() string {
@@ -40,6 +41,12 @@ func (s ServerConfig) Address() string {
return fmt.Sprintf(":%d", s.Port)
}
type CORSConfig struct {
// AllowedOrigins 是允许浏览器跨域访问的 Origin 白名单,必须包含协议和域名。
// 留空表示不允许跨域请求;同源请求通常不会携带 Origin,不受影响。
AllowedOrigins []string `yaml:"allowedOrigins"`
}
type DBConfig struct {
Type string `yaml:"type"`
DSN string `yaml:"dsn"`
+37
View File
@@ -0,0 +1,37 @@
package config
import (
"os"
"path/filepath"
"testing"
)
func TestLoadReadsCORSAllowedOrigins(t *testing.T) {
path := filepath.Join(t.TempDir(), "config.yaml")
content := []byte(`server:
port: 8083
cors:
allowedOrigins:
- https://console.example.com
- http://localhost:3000
`)
if err := os.WriteFile(path, content, 0600); err != nil {
t.Fatalf("WriteFile() error = %v", err)
}
cfg, err := Load(path)
if err != nil {
t.Fatalf("Load() error = %v", err)
}
got := cfg.Server.CORS.AllowedOrigins
want := []string{"https://console.example.com", "http://localhost:3000"}
if len(got) != len(want) {
t.Fatalf("len(AllowedOrigins)=%d want %d", len(got), len(want))
}
for i := range want {
if got[i] != want[i] {
t.Fatalf("AllowedOrigins[%d]=%q want %q", i, got[i], want[i])
}
}
}