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))

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

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.

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