From 110fe4b0aa1f2760a3366ae147144ae3e781ae5a Mon Sep 17 00:00:00 2001 From: yusing Date: Wed, 21 Jan 2026 22:36:22 +0800 Subject: [PATCH] feat(api): enhance API handler to support unauthenticated local access - Updated NewHandler function to accept a requireAuth parameter for authentication control. - Introduced a new local API server that allows unauthenticated access when LocalAPIHTTPAddr is set. - Adjusted server startup logic to handle both authenticated and unauthenticated API routes. --- cmd/main.go | 11 ++++++++++- internal/api/handler.go | 6 +++--- internal/common/env.go | 5 +++++ 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/cmd/main.go b/cmd/main.go index 11c1f20d..f227da7b 100755 --- a/cmd/main.go +++ b/cmd/main.go @@ -69,9 +69,18 @@ func main() { server.StartServer(task.RootTask("api_server", false), server.Options{ Name: "api", HTTPAddr: common.APIHTTPAddr, - Handler: api.NewHandler(), + Handler: api.NewHandler(true), }) + // Local API Handler is used for unauthenticated access. + if common.LocalAPIHTTPAddr != "" { + server.StartServer(task.RootTask("local_api_server", false), server.Options{ + Name: "local_api", + HTTPAddr: common.LocalAPIHTTPAddr, + Handler: api.NewHandler(false), + }) + } + listenDebugServer() uptime.Poller.Start() diff --git a/internal/api/handler.go b/internal/api/handler.go index 067ffc90..b64c1ca2 100644 --- a/internal/api/handler.go +++ b/internal/api/handler.go @@ -36,7 +36,7 @@ import ( // @externalDocs.description GoDoxy Docs // @externalDocs.url https://docs.godoxy.dev -func NewHandler() *gin.Engine { +func NewHandler(requireAuth bool) *gin.Engine { if !common.IsDebug { gin.SetMode("release") } @@ -47,7 +47,7 @@ func NewHandler() *gin.Engine { r.GET("/api/v1/version", apiV1.Version) - if auth.IsEnabled() { + if auth.IsEnabled() && requireAuth { v1Auth := r.Group("/api/v1/auth") { v1Auth.HEAD("/check", authApi.Check) @@ -60,7 +60,7 @@ func NewHandler() *gin.Engine { } v1 := r.Group("/api/v1") - if auth.IsEnabled() { + if auth.IsEnabled() && requireAuth { v1.Use(AuthMiddleware()) } if common.APISkipOriginCheck { diff --git a/internal/common/env.go b/internal/common/env.go index 2121612f..f181d0c3 100644 --- a/internal/common/env.go +++ b/internal/common/env.go @@ -30,6 +30,11 @@ var ( APIHTTPPort, APIHTTPURL = env.GetAddrEnv("API_ADDR", "127.0.0.1:8888", "http") + LocalAPIHTTPAddr, + LocalAPIHTTPHost, + LocalAPIHTTPPort, + LocalAPIHTTPURL = env.GetAddrEnv("LOCAL_API_ADDR", "", "http") + APIJWTSecure = env.GetEnvBool("API_JWT_SECURE", true) APIJWTSecret = decodeJWTKey(env.GetEnvString("API_JWT_SECRET", "")) APIJWTTokenTTL = env.GetEnvDuation("API_JWT_TOKEN_TTL", 24*time.Hour)