From 0d5994a1d673b5c18a6b71722c6d637b16a4dc49 Mon Sep 17 00:00:00 2001 From: Tomas Vik Date: Wed, 16 Aug 2023 14:59:26 +0200 Subject: [PATCH] feat: handle taken port --- .air.toml | 2 +- main.go | 24 ++++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/.air.toml b/.air.toml index 16e413a..db5e35e 100644 --- a/.air.toml +++ b/.air.toml @@ -15,7 +15,7 @@ tmp_dir = "tmp" full_bin = "" include_dir = [] include_ext = ["go", "tpl", "tmpl", "html", "css"] - include_file = [] + include_file = ["gpic"] kill_delay = "0s" log = "build-errors.log" poll = false diff --git a/main.go b/main.go index 6c3afd6..989cc55 100644 --- a/main.go +++ b/main.go @@ -7,6 +7,7 @@ import ( "html/template" "io" "log" + "net" "net/http" "os" "os/exec" @@ -153,6 +154,18 @@ func main() { go func() { defer wg.Done() err = http.ListenAndServe(addr, nil) + if err != nil { + fmt.Printf("Warning: %s\n", err) + err = nil + port, err := findAvailablePort() + if err != nil { + fmt.Printf("Error: %s\n", err) + return + } + addr = fmt.Sprintf("localhost:%d", port) + url = fmt.Sprintf("http://%s", addr) + err = http.ListenAndServe(addr, nil) + } if err != nil { fmt.Printf("Error: %s\n", err) } @@ -200,3 +213,14 @@ func isImageFile(filename string) bool { ext := filepath.Ext(filename) return ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".gif" } + +func findAvailablePort() (int, error) { + listener, err := net.Listen("tcp", "localhost:0") // 0 indicates a random available port + if err != nil { + return 0, err + } + defer listener.Close() + + addr := listener.Addr().(*net.TCPAddr) + return addr.Port, nil +}