From 296d218e6704e73b3261bca6f5f72b3569cf899b Mon Sep 17 00:00:00 2001 From: spf13 Date: Thu, 15 May 2014 15:07:46 -0400 Subject: [PATCH] Better handling of when the specified port is already in use --- commands/server.go | 14 ++++++++++++++ helpers/general.go | 15 +++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/commands/server.go b/commands/server.go index ed04f0410..2b2794fe8 100644 --- a/commands/server.go +++ b/commands/server.go @@ -15,6 +15,7 @@ package commands import ( "fmt" + "net" "net/http" "os" "strconv" @@ -56,6 +57,19 @@ func server(cmd *cobra.Command, args []string) { BaseUrl = "http://" + BaseUrl } + l, err := net.Listen("tcp", ":"+strconv.Itoa(serverPort)) + if err == nil { + l.Close() + } else { + jww.ERROR.Println("port", serverPort, "already in use, attempting to use an available port") + sp, err := helpers.FindAvailablePort() + if err != nil { + jww.ERROR.Println("Unable to find alternative port to use") + jww.ERROR.Fatalln(err) + } + serverPort = sp.Port + } + if serverAppend { viper.Set("BaseUrl", strings.TrimSuffix(BaseUrl, "/")+":"+strconv.Itoa(serverPort)) } else { diff --git a/helpers/general.go b/helpers/general.go index 208b0d2d3..a2ebac9e1 100644 --- a/helpers/general.go +++ b/helpers/general.go @@ -15,6 +15,8 @@ package helpers import ( "bytes" + "fmt" + "net" "strings" ) @@ -49,3 +51,16 @@ func StripHTML(s string) string { } return output } + +func FindAvailablePort() (*net.TCPAddr, error) { + l, err := net.Listen("tcp", ":0") + if err == nil { + defer l.Close() + addr := l.Addr() + if a, ok := addr.(*net.TCPAddr); ok { + return a, nil + } + return nil, fmt.Errorf("Unable to obtain a valid tcp port. %v", addr) + } + return nil, err +}