From 9fc43d7d65a2cea43c3109e0a1cecc579edcfcfc Mon Sep 17 00:00:00 2001 From: expiteRz Date: Wed, 3 Jul 2024 02:13:17 +0900 Subject: [PATCH] Refactor port usage check - Return value could be smarter so do again later --- web/port_check.go | 8 ++++---- web/web.go | 7 +++---- web/web_d.go | 7 +++---- 3 files changed, 10 insertions(+), 12 deletions(-) diff --git a/web/port_check.go b/web/port_check.go index 9962f04..e851d85 100644 --- a/web/port_check.go +++ b/web/port_check.go @@ -7,18 +7,18 @@ import ( "time" ) -func portCheck(address string, port int) (int, error) { +func portCheck(address string, port int) (string, error) { for { conn, err := net.DialTimeout("tcp", fmt.Sprint(address, ":", port), time.Second) if err != nil { - return port, nil + return fmt.Sprint(address, ":", port), nil } if conn != nil { newPort := port + 1 - log.Println(address, "is already in use.", fmt.Sprint(address, ":", newPort), "will use instead.") + log.Println(fmt.Sprint(address, ":", port), "is already in use.", fmt.Sprint(address, ":", newPort), "will use instead.") port = newPort continue } - return port, nil + return fmt.Sprint(address, ":", port), nil } } diff --git a/web/web.go b/web/web.go index a0418e0..ab47e8e 100644 --- a/web/web.go +++ b/web/web.go @@ -99,9 +99,8 @@ func setupRoutes() *http.ServeMux { } func StartServer() { - port, err := portCheck(utils.LoadedConfig.ServerIp, utils.LoadedConfig.ServerPort) - address := fmt.Sprint(utils.LoadedConfig.ServerIp, ":", port) - l, err := net.Listen("tcp", address) + addr, err := portCheck(utils.LoadedConfig.ServerIp, utils.LoadedConfig.ServerPort) + l, err := net.Listen("tcp", addr) if err != nil { log.Fatalln(err) return @@ -109,7 +108,7 @@ func StartServer() { mux := setupRoutes() // There is no way to print the notification that the user can access after serving, so print it here instead log.SetPrefix("[Web] ") - log.Printf("Start hosting on http://%s\n", address) + log.Printf("Start hosting on http://%s\n", addr) if err = http.Serve(l, mux); err != nil { log.SetPrefix("[Web] ") diff --git a/web/web_d.go b/web/web_d.go index 3f7f8b0..a39fe1a 100644 --- a/web/web_d.go +++ b/web/web_d.go @@ -110,9 +110,8 @@ func setupRoutes() *http.ServeMux { } func StartServer() { - port, err := portCheck(utils.LoadedConfig.ServerIp, utils.LoadedConfig.ServerPort) - address := fmt.Sprint(utils.LoadedConfig.ServerIp, ":", port) - l, err := net.Listen("tcp", address) + addr, err := portCheck(utils.LoadedConfig.ServerIp, utils.LoadedConfig.ServerPort) + l, err := net.Listen("tcp", addr) if err != nil { log.Fatalln(err) return @@ -120,7 +119,7 @@ func StartServer() { mux := setupRoutes() // There is no way to print the notification that the user can access after serving, so print it here instead log.SetPrefix("[Web] ") - log.Printf("Start hosting on http://%s\n", address) + log.Printf("Start hosting on http://%s\n", addr) if err = http.Serve(l, mux); err != nil { log.SetPrefix("[Web] ")