![Go Standard Library Cookbook](https://wfqqreader-1252317822.image.myqcloud.com/cover/179/36700179/b_36700179.jpg)
上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:
![](https://epubservercos.yuewen.com/D3CFF8/19470397101585106/epubprivate/OEBPS/Images/10deaa7c-c4af-4ceb-b13c-4d3fda3c7bb5.png?sign=1739585776-P2OfIAbVBBXIxVUJKTZjXXbMFGnYIJ26-0-92631cbe8967226cabbfbd5a43ea8cc6)
- 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:
![](https://epubservercos.yuewen.com/D3CFF8/19470397101585106/epubprivate/OEBPS/Images/aa749e9a-6241-4830-b558-2ff06a7506d5.png?sign=1739585776-39YwUKf69lxZxSGk7q1iayLGiTbdmUpl-0-53297c3b225c1c6a5cb9256252168fc2)
- 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:
![](https://epubservercos.yuewen.com/D3CFF8/19470397101585106/epubprivate/OEBPS/Images/20b7ef63-0921-49c4-94f4-3c6f1498de02.png?sign=1739585776-EWpy5ReBKgTeY4BdCOgej4lEsQpuyl0A-0-1d58e67b58fa63f7f81b56de5a3b7ad8)