From 746eb82f67e2947340ee0439db81555498622d3b Mon Sep 17 00:00:00 2001 From: leo Date: Thu, 4 May 2023 21:28:30 +0200 Subject: [PATCH] go: make sure flags are properly checked --- app/settings/helper.go | 16 ++++++++++++++++ app/settings/settings.go | 24 +++++++++++++++--------- run.go | 2 +- 3 files changed, 32 insertions(+), 10 deletions(-) create mode 100644 app/settings/helper.go diff --git a/app/settings/helper.go b/app/settings/helper.go new file mode 100644 index 0000000..fd4e4c5 --- /dev/null +++ b/app/settings/helper.go @@ -0,0 +1,16 @@ +package settings + +import "flag" + +// as per https://stackoverflow.com/a/54747682. +func isFlagPassed(name string) bool { + found := false + + flag.Visit(func(f *flag.Flag) { + if f.Name == name { + found = true + } + }) + + return found +} diff --git a/app/settings/settings.go b/app/settings/settings.go index 67dc226..150a902 100644 --- a/app/settings/settings.go +++ b/app/settings/settings.go @@ -45,19 +45,25 @@ func (s *Settings) Consolidate(conf *config.Config, host *string, port *int, dev overrideMsg := "overriding '%s' based on a flag: %+v" - if h := *host; h != "unset" && h != conf.Host { - log.Debugf(overrideMsg, "host", h) - s.SetHost(h) + if isFlagPassed("host") { + if h := *host; h != "unset" && h != conf.Host { + log.Debugf(overrideMsg, "host", h) + s.SetHost(h) + } } - if p := *port; p != 0 && p > 0 && p < 65536 && p != conf.Port { - log.Debugf(overrideMsg, "port", p) - s.SetPort(p) + if isFlagPassed("port") { + if p := *port; p > 0 && p < 65536 && p != conf.Port { + log.Debugf(overrideMsg, "port", p) + s.SetPort(p) + } } - if d := *devel; d != conf.DevelMode { - log.Debugf(overrideMsg, "develMode", d) - s.SetIsDevel(d) + if isFlagPassed("devel") { + if d := *devel; d != conf.DevelMode { + log.Debugf(overrideMsg, "develMode", d) + s.SetIsDevel(d) + } } s.SetVersion(version) diff --git a/run.go b/run.go index e24bd0a..7200afd 100644 --- a/run.go +++ b/run.go @@ -52,7 +52,7 @@ along with this program. If not, see .` var ( host = flag.String("host", "unset", "host address to listen on") - port = flag.Int("port", 0, "TCP port to listen on") + port = flag.Int("port", -1, "TCP port to listen on") configFlag = flag.String("config", "config.dhall", "Default path of the config file") devel = flag.Bool("devel", false, "Run the application in dev mode, connect to a local browser-sync instance for hot-reloading") license = flag.Bool("license", false, "Print licensing information and exit")