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 }