Go Standard Library Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it…

  1. Open the console and create the folder chapter01/recipe04.
  2. Navigate to the directory.
  1. 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)
}
  1. Execute the code by calling DB_CONN=db:/user@example && go run get.go in the Terminal.
  2. See the output in the Terminal:
  1. 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)
}
  1. Execute the code by calling unset DB_CONN && go run lookup.go in the Terminal.
  2. See the output in the Terminal:
  1. 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
}
  1. Run the code by executing go run main.go.
  2. See the output in the Terminal: