Skip to content

Commit

Permalink
feat: handle taken port
Browse files Browse the repository at this point in the history
  • Loading branch information
viktomas committed Aug 16, 2023
1 parent d87fba7 commit 0d5994a
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
2 changes: 1 addition & 1 deletion .air.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
24 changes: 24 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"html/template"
"io"
"log"
"net"
"net/http"
"os"
"os/exec"
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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
}

0 comments on commit 0d5994a

Please sign in to comment.