allocate local port dynamically, fixes #290 (#292)

This commit is contained in:
Glen De Cauwsemaecker 2017-04-15 21:37:47 -05:00 committed by siddontang
parent 9f6a59ea1a
commit 80ea7b8bca
2 changed files with 34 additions and 18 deletions

View File

@ -93,6 +93,7 @@ type Config struct {
FileName string `toml:"-"` FileName string `toml:"-"`
// Addr can be empty to assign a local address dynamically
Addr string `toml:"addr"` Addr string `toml:"addr"`
AddrUnixSocketPerm string `toml:"addr_unixsocketperm"` AddrUnixSocketPerm string `toml:"addr_unixsocketperm"`
@ -136,13 +137,14 @@ func NewConfigWithFile(fileName string) (*Config, error) {
return nil, err return nil, err
} }
if cfg, err := NewConfigWithData(data); err != nil { cfg, err := NewConfigWithData(data)
if err != nil {
return nil, err return nil, err
} else { }
cfg.FileName = fileName cfg.FileName = fileName
return cfg, nil return cfg, nil
} }
}
func NewConfigWithData(data []byte) (*Config, error) { func NewConfigWithData(data []byte) (*Config, error) {
cfg := NewConfigDefault() cfg := NewConfigDefault()
@ -203,9 +205,9 @@ func NewConfigDefault() *Config {
func getDefault(d int, s int) int { func getDefault(d int, s int) int {
if s <= 0 { if s <= 0 {
return d return d
} else {
return s
} }
return s
} }
func (cfg *Config) adjust() { func (cfg *Config) adjust() {

View File

@ -1,6 +1,7 @@
package server package server
import ( import (
"fmt"
"net" "net"
"net/http" "net/http"
"os" "os"
@ -55,9 +56,9 @@ type App struct {
func netType(s string) string { func netType(s string) string {
if strings.Contains(s, "/") { if strings.Contains(s, "/") {
return "unix" return "unix"
} else {
return "tcp"
} }
return "tcp"
} }
func NewApp(cfg *config.Config) (*App, error) { func NewApp(cfg *config.Config) (*App, error) {
@ -88,6 +89,7 @@ func NewApp(cfg *config.Config) (*App, error) {
return nil, err return nil, err
} }
if cfg.Addr != "" {
addrNetType := netType(cfg.Addr) addrNetType := netType(cfg.Addr)
if app.listener, err = net.Listen(addrNetType, cfg.Addr); err != nil { if app.listener, err = net.Listen(addrNetType, cfg.Addr); err != nil {
@ -103,6 +105,14 @@ func NewApp(cfg *config.Config) (*App, error) {
return nil, err return nil, err
} }
} }
} else {
app.listener, err = net.Listen("tcp", "127.0.0.1:0")
if err != nil {
if app.listener, err = net.Listen("tcp6", "[::1]:0"); err != nil {
return nil, fmt.Errorf("app: failed to listen on a port: %v", err)
}
}
}
if len(cfg.HttpAddr) > 0 { if len(cfg.HttpAddr) > 0 {
if app.httpListener, err = net.Listen(netType(cfg.HttpAddr), cfg.HttpAddr); err != nil { if app.httpListener, err = net.Listen(netType(cfg.HttpAddr), cfg.HttpAddr); err != nil {
@ -227,3 +237,7 @@ func (app *App) httpServe() {
func (app *App) Ledis() *ledis.Ledis { func (app *App) Ledis() *ledis.Ledis {
return app.ldb return app.ldb
} }
func (app *App) Address() string {
return app.listener.Addr().String()
}