diff --git a/config/config.go b/config/config.go index f0ac896..32c75a4 100644 --- a/config/config.go +++ b/config/config.go @@ -93,6 +93,7 @@ type Config struct { FileName string `toml:"-"` + // Addr can be empty to assign a local address dynamically Addr string `toml:"addr"` AddrUnixSocketPerm string `toml:"addr_unixsocketperm"` @@ -136,12 +137,13 @@ func NewConfigWithFile(fileName string) (*Config, error) { return nil, err } - if cfg, err := NewConfigWithData(data); err != nil { + cfg, err := NewConfigWithData(data) + if err != nil { return nil, err - } else { - cfg.FileName = fileName - return cfg, nil } + + cfg.FileName = fileName + return cfg, nil } func NewConfigWithData(data []byte) (*Config, error) { @@ -203,9 +205,9 @@ func NewConfigDefault() *Config { func getDefault(d int, s int) int { if s <= 0 { return d - } else { - return s } + + return s } func (cfg *Config) adjust() { diff --git a/server/app.go b/server/app.go index 078d43d..7047f5c 100644 --- a/server/app.go +++ b/server/app.go @@ -1,6 +1,7 @@ package server import ( + "fmt" "net" "net/http" "os" @@ -55,9 +56,9 @@ type App struct { func netType(s string) string { if strings.Contains(s, "/") { return "unix" - } else { - return "tcp" } + + return "tcp" } func NewApp(cfg *config.Config) (*App, error) { @@ -88,19 +89,28 @@ func NewApp(cfg *config.Config) (*App, error) { return nil, err } - addrNetType := netType(cfg.Addr) + if cfg.Addr != "" { + addrNetType := netType(cfg.Addr) - if app.listener, err = net.Listen(addrNetType, cfg.Addr); err != nil { - return nil, err - } - - if addrNetType == "unix" && len(cfg.AddrUnixSocketPerm) > 0 { - var perm int64 - if perm, err = strconv.ParseInt(cfg.AddrUnixSocketPerm, 8, 32); err != nil { + if app.listener, err = net.Listen(addrNetType, cfg.Addr); err != nil { return nil, err } - if err = os.Chmod(cfg.Addr, os.FileMode(perm)); err != nil { - return nil, err + + if addrNetType == "unix" && len(cfg.AddrUnixSocketPerm) > 0 { + var perm int64 + if perm, err = strconv.ParseInt(cfg.AddrUnixSocketPerm, 8, 32); err != nil { + return nil, err + } + if err = os.Chmod(cfg.Addr, os.FileMode(perm)); err != nil { + 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) + } } } @@ -227,3 +237,7 @@ func (app *App) httpServe() { func (app *App) Ledis() *ledis.Ledis { return app.ldb } + +func (app *App) Address() string { + return app.listener.Addr().String() +}