上QQ阅读APP看书,第一时间看更新
How to do it…
- Open the console and create the folder chapter01/recipe04.
- Navigate to the directory.
- Create the get.go file with the following content:
package main
import (
"log"
"os"
)
func main() {
connStr := os.Getenv("DB_CONN")
log.Printf("Connection string: %s\n", connStr)
}
- Execute the code by calling DB_CONN=db:/user@example && go run get.go in the Terminal.
- See the output in the Terminal:
- Create the lookup.go file with the following content:
package main
import (
"log"
"os"
)
func main() {
key := "DB_CONN"
connStr, ex := os.LookupEnv(key)
if !ex {
log.Printf("The env variable %s is not set.\n", key)
}
fmt.Println(connStr)
}
- Execute the code by calling unset DB_CONN && go run lookup.go in the Terminal.
- See the output in the Terminal:
- Create the main.go file with the following content:
package main
import (
"log"
"os"
)
func main() {
key := "DB_CONN"
// Set the environmental variable.
os.Setenv(key, "postgres://as:as@example.com/pg?
sslmode=verify-full")
val := GetEnvDefault(key, "postgres://as:as@localhost/pg?
sslmode=verify-full")
log.Println("The value is :" + val)
os.Unsetenv(key)
val = GetEnvDefault(key, "postgres://as:as@127.0.0.1/pg?
sslmode=verify-full")
log.Println("The default value is :" + val)
}
func GetEnvDefault(key, defVal string) string {
val, ex := os.LookupEnv(key)
if !ex {
return defVal
}
return val
}
- Run the code by executing go run main.go.
- See the output in the Terminal: