From 119938d4b94fdf713efb3340ebd4ba5f3286f520 Mon Sep 17 00:00:00 2001 From: Carl Jackson Date: Wed, 8 Oct 2014 00:58:55 -0700 Subject: [PATCH] Add bind.Sniff to expose default selection logic This allows users who do not wish to use bind.WithFlag() to still take advantage of bind's magical listener selection logic. Fixes #68. --- bind/bind.go | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/bind/bind.go b/bind/bind.go index 9228f5a..8e783bf 100644 --- a/bind/bind.go +++ b/bind/bind.go @@ -52,14 +52,8 @@ func init() { // of the default socket will be reasonable for use in your circumstance. func WithFlag() { defaultBind := ":8000" - if bind := os.Getenv("GOJI_BIND"); bind != "" { - defaultBind = bind - } else if usingEinhorn() { - defaultBind = "einhorn@0" - } else if usingSystemd() { - defaultBind = "fd@3" - } else if port := os.Getenv("PORT"); port != "" { - defaultBind = ":" + port + if s := Sniff(); s != "" { + defaultBind = s } flag.StringVar(&bind, "bind", defaultBind, `Address to bind on. If this value has a colon, as in ":8000" or @@ -74,6 +68,24 @@ func WithFlag() { (systemd), and ":8000" (fallback) based on its environment.`) } +// Sniff attempts to select a sensible default bind string by examining its +// environment. It examines the GOJI_BIND environment variable, Einhorn, +// systemd, and the PORT environment variable, in that order, selecting the +// first plausible option. It returns the empty string if no sensible default +// could be extracted from the environment. +func Sniff() string { + if bind := os.Getenv("GOJI_BIND"); bind != "" { + return bind + } else if usingEinhorn() { + return "einhorn@0" + } else if usingSystemd() { + return "fd@3" + } else if port := os.Getenv("PORT"); port != "" { + return ":" + port + } + return "" +} + func listenTo(bind string) (net.Listener, error) { if strings.Contains(bind, ":") { return net.Listen("tcp", bind)