summaryrefslogtreecommitdiffstats
path: root/src/server.go
diff options
context:
space:
mode:
authorJunegunn Choi <junegunn.c@gmail.com>2023-03-19 15:42:47 +0900
committerJunegunn Choi <junegunn.c@gmail.com>2023-03-19 15:48:39 +0900
commitfcd7e8768dc4a23f6e4f1aec57c9d2236ebe7fae (patch)
tree7d39262b031120ceebf516a0e844b4ac26766edd /src/server.go
parent3c34dd82750ca61a1ee7f329ed47fe01e6d1ee30 (diff)
Omit port number in `--listen` for automatic port assignment
Close #3200
Diffstat (limited to 'src/server.go')
-rw-r--r--src/server.go22
1 files changed, 17 insertions, 5 deletions
diff --git a/src/server.go b/src/server.go
index 2912b1a4..89a7938c 100644
--- a/src/server.go
+++ b/src/server.go
@@ -19,14 +19,26 @@ const (
maxContentLength = 1024 * 1024
)
-func startHttpServer(port int, channel chan []*action) error {
- if port == 0 {
- return nil
+func startHttpServer(port int, channel chan []*action) (error, int) {
+ if port < 0 {
+ return nil, port
}
listener, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", port))
if err != nil {
- return fmt.Errorf("port not available: %d", port)
+ return fmt.Errorf("port not available: %d", port), port
+ }
+ if port == 0 {
+ addr := listener.Addr().String()
+ parts := strings.SplitN(addr, ":", 2)
+ if len(parts) < 2 {
+ return fmt.Errorf("cannot extract port: %s", addr), port
+ }
+ var err error
+ port, err = strconv.Atoi(parts[1])
+ if err != nil {
+ return err, port
+ }
}
go func() {
@@ -45,7 +57,7 @@ func startHttpServer(port int, channel chan []*action) error {
listener.Close()
}()
- return nil
+ return nil, port
}
// Here we are writing a simplistic HTTP server without using net/http