user7898461
user7898461

Reputation:

Default value pattern for Golang

I have this:

port := os.Getenv("huru_api_port") ||  ":8000"

that doesn't compile, Golang doesn't recognize that as syntax for defaulting to ":8000" if huru_api_port is empty/undefined.

Is there a good way to do this? On a side note, why is it ":8000" instead of "8000", for example:

log.Fatal(http.ListenAndServe(":8000", router))

Upvotes: 4

Views: 3597

Answers (3)

Adam Smith
Adam Smith

Reputation: 54193

os.LookupEnv will return the environment variable as a string and a boolean indicating whether or not the variable was set, so you'll either get

v, ok = "something", true
// or, if the env var isn't set
v, ok = "", false
// or, if the env var is set but empty:
v, ok = "", true

Use it like:

var port string
var ok bool
if port, ok = os.LookupEnv("huru_api_port"); !ok {
    port = ":8000"
}

Upvotes: 3

poy
poy

Reputation: 10507

I would use LookupEnv. It offers a boolean that will be false if the variable is not set.

The :8000 means the listener will bind to all the network interfaces. You can think of it differing from 127.0.0.1:8000 which would only bind to the loopback interface.

Upvotes: 1

sma
sma

Reputation: 9597

There's no easy shorthand way to do that in Go, but for your case, you can use LookupEnv instead, which returns the value (if set) and a boolean indicating whether the key was found in the environment:

https://golang.org/pkg/os/#LookupEnv

Upvotes: 1

Related Questions