From e769f67699ed7e5cbc79a61632940d3424777726 Mon Sep 17 00:00:00 2001 From: shaw Date: Fri, 19 Dec 2025 11:21:58 +0800 Subject: [PATCH] =?UTF-8?q?fix(setup):=20=E6=94=AF=E6=8C=81=E4=BB=8E?= =?UTF-8?q?=E9=85=8D=E7=BD=AE=E6=96=87=E4=BB=B6=E8=AF=BB=E5=8F=96=20Setup?= =?UTF-8?q?=20Wizard=20=E7=9B=91=E5=90=AC=E5=9C=B0=E5=9D=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Setup Wizard 之前硬编码使用 8080 端口,现在支持从 config.yaml 或 环境变量 (SERVER_HOST, SERVER_PORT) 读取监听地址,方便用户在端口 被占用时使用其他地址启动初始化向导。 --- backend/cmd/server/main.go | 7 +++++-- backend/internal/config/config.go | 26 ++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/backend/cmd/server/main.go b/backend/cmd/server/main.go index ae000119..ac10b322 100644 --- a/backend/cmd/server/main.go +++ b/backend/cmd/server/main.go @@ -15,6 +15,7 @@ import ( "syscall" "time" + "sub2api/internal/config" "sub2api/internal/handler" "sub2api/internal/middleware" "sub2api/internal/setup" @@ -94,8 +95,10 @@ func runSetupServer() { r.Use(web.ServeEmbeddedFrontend()) } - addr := ":8080" - log.Printf("Setup wizard available at http://localhost%s", addr) + // Get server address from config.yaml or environment variables (SERVER_HOST, SERVER_PORT) + // This allows users to run setup on a different address if needed + addr := config.GetServerAddress() + log.Printf("Setup wizard available at http://%s", addr) log.Println("Complete the setup wizard to configure Sub2API") if err := r.Run(addr); err != nil { diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index b4120201..d8836e92 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -203,3 +203,29 @@ func (c *Config) Validate() error { } return nil } + +// GetServerAddress returns the server address (host:port) from config file or environment variable. +// This is a lightweight function that can be used before full config validation, +// such as during setup wizard startup. +// Priority: config.yaml > environment variables > defaults +func GetServerAddress() string { + v := viper.New() + v.SetConfigName("config") + v.SetConfigType("yaml") + v.AddConfigPath(".") + v.AddConfigPath("./config") + v.AddConfigPath("/etc/sub2api") + + // Support SERVER_HOST and SERVER_PORT environment variables + v.AutomaticEnv() + v.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) + v.SetDefault("server.host", "0.0.0.0") + v.SetDefault("server.port", 8080) + + // Try to read config file (ignore errors if not found) + _ = v.ReadInConfig() + + host := v.GetString("server.host") + port := v.GetInt("server.port") + return fmt.Sprintf("%s:%d", host, port) +}