From adc5055da43404ae8cee3278a0d10c4b86750518 Mon Sep 17 00:00:00 2001 From: Matthieu 'JP' DERASSE Date: Tue, 3 Jan 2023 21:53:45 +0000 Subject: [PATCH] feat(server): Add basic listenAddress getter from flag or env --- server/server.go | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 server/server.go diff --git a/server/server.go b/server/server.go new file mode 100644 index 0000000..dd0c497 --- /dev/null +++ b/server/server.go @@ -0,0 +1,37 @@ +package server + +import ( + "flag" + "fmt" + "os" + + "github.com/asaskevich/govalidator" +) + +// GetListenAddressFromEnvOrFlags will check flag --host and --port to construct the listen address +// If they doesn't exist it will fallback on HOST and PORT environment variable and finally fallback +// to the default value localhost:8080. +func GetListenAddressFromEnvOrFlags() (string, error) { + host := os.Getenv("HOST") + port := os.Getenv("PORT") + + if host == "" { + host = "localhost" + } + if port == "" { + port = "8080" + } + + pHost := flag.String("host", host, "Host address to listen to") + pPort := flag.String("port", port, "Port to listen to") + + if govalidator.IsHost(*pHost) { + return "", fmt.Errorf("provided 'host' is invalid") + } + + if govalidator.IsPort(*pPort) { + return "", fmt.Errorf("provided 'port' is invalid") + } + + return fmt.Sprintf("%s:%s", *pHost, *pPort), nil +}