Skip to content

Commit

Permalink
Refactor port usage check
Browse files Browse the repository at this point in the history
- Return value could be smarter so do again later
  • Loading branch information
expiteRz committed Jul 2, 2024
1 parent 265d235 commit 9fc43d7
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 12 deletions.
8 changes: 4 additions & 4 deletions web/port_check.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
7 changes: 3 additions & 4 deletions web/web.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,17 +99,16 @@ 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
}
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] ")
Expand Down
7 changes: 3 additions & 4 deletions web/web_d.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,17 +110,16 @@ 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
}
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] ")
Expand Down

0 comments on commit 9fc43d7

Please sign in to comment.