feat(server): Add basic listenAddress getter from flag or env
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Matthieu 'JP' DERASSE 2023-01-03 21:53:45 +00:00
parent c040c1fc78
commit adc5055da4
Signed by: mderasse
GPG Key ID: 55141C777B16A705

37
server/server.go Normal file
View File

@ -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
}