gocommon/server/server.go
Matthieu 'JP' DERASSE 44ff19e779
Some checks failed
continuous-integration/drone/push Build is failing
feat(server): Handle creation of a webserver
2023-01-09 19:44:29 +00:00

38 lines
876 B
Go

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
}