From 9039ef79cf21a1d8381095cc0c8b8b30584f2150 Mon Sep 17 00:00:00 2001 From: Michael Engelhardt Date: Tue, 17 Nov 2020 23:53:57 +0100 Subject: [PATCH] add parameterization for host and port Host and port can be specified by either a environment variable or a dedicated command line parameter. Command line parameters will be preferred over environment variables, which will be preferred over the application defaults. --- main.go | 40 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/main.go b/main.go index 0d3ffcb9..9427307e 100644 --- a/main.go +++ b/main.go @@ -3,9 +3,12 @@ package main import ( "bytes" "compress/gzip" + "flag" + "fmt" "log" "net/http" "os" + "strconv" "strings" "time" @@ -21,9 +24,41 @@ var ( cachedServiceResults []byte cachedServiceResultsGzipped []byte cachedServiceResultsTimestamp time.Time + port int + host string ) +func init() { + // Customizing priority: + // (1) command line parameters will be preferred over + // (2) environment variables will be preferred over + // (3) application defaults + + // set defaults for the case that neither an environment variable nor a + // command line parameter is passed + var defaultHost = "" + var defaultPort = 8080 + + // assume set if the is a valid port number + if p, err := strconv.Atoi(os.Getenv("GATUS_CONFIG_PORT")); err == nil && p > 0 { + defaultPort = p + } + + // explicitly asked if the user has set a the environment variable to + // blank / empty in order to allow listening on all interfaces + if h, set := os.LookupEnv("GATUS_CONFIG_HOST"); set == true { + defaultHost = h + } + + flag.IntVar(&port, "port", defaultPort, "port to listen (default: 8080)") + flag.IntVar(&port, "p", defaultPort, "port to listen (default: 8080 ; shorthand)") + flag.StringVar(&host, "host", defaultHost, "host to listen on (default all interfaces on host)") + flag.StringVar(&host, "host", defaultHost, "host to listen on (default all interfaces on host; shorthand)") +} + func main() { + flag.Parse() + cfg := loadConfiguration() resultsHandler := serviceResultsHandler if cfg.Security != nil && cfg.Security.IsValid() { @@ -35,9 +70,10 @@ func main() { if cfg.Metrics { http.Handle("/metrics", promhttp.Handler()) } - log.Println("[main][main] Listening on port 8080") + + log.Printf("[main][main] Listening on %s:%d", host, port) go watchdog.Monitor(cfg) - log.Fatal(http.ListenAndServe(":8080", nil)) + log.Fatal(http.ListenAndServe(fmt.Sprintf("%s:%d", host, port), nil)) } func loadConfiguration() *config.Config {