mirror of
https://github.com/gohugoio/hugo.git
synced 2024-12-22 20:31:23 +00:00
Better handling of when the specified port is already in use
This commit is contained in:
parent
b520f8852d
commit
296d218e67
2 changed files with 29 additions and 0 deletions
|
@ -15,6 +15,7 @@ package commands
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
@ -56,6 +57,19 @@ func server(cmd *cobra.Command, args []string) {
|
||||||
BaseUrl = "http://" + BaseUrl
|
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 {
|
if serverAppend {
|
||||||
viper.Set("BaseUrl", strings.TrimSuffix(BaseUrl, "/")+":"+strconv.Itoa(serverPort))
|
viper.Set("BaseUrl", strings.TrimSuffix(BaseUrl, "/")+":"+strconv.Itoa(serverPort))
|
||||||
} else {
|
} else {
|
||||||
|
|
|
@ -15,6 +15,8 @@ package helpers
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -49,3 +51,16 @@ func StripHTML(s string) string {
|
||||||
}
|
}
|
||||||
return output
|
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
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in a new issue