1
package main
import (
"log"
"os"
)
func main() {
connStr := os.Getenv("DB_CONN")
log.Printf("Connection string: %s
", connStr)
}
/*
export DB_CONN="mysql:username@scdfaf123"
./go_web
2018/03/17 21:58:12 Connection string: mysql:username@scdfaf123
*/
2 不存在则报错
package main
import (
"fmt"
"log"
"os"
)
func main() {
key := "DB_CONN"
connStr, ex := os.LookupEnv(key)
if !ex {
log.Printf("The env variable %s is not set.
", key)
}
fmt.Println(connStr)
}
/*
export DB_CONN="mysql:username@scdfaf123"
./go_web
mysql:username@scdfaf123
*/
3 设置获取删除环境变量
./go_web
2018/03/17 22:01:57 The value is :postgres://as:as@example.com/pg?sslmode=verify-full
2018/03/17 22:01:57 The default value is :postgres://as:as@127.0.0.1/pg?sslmode=verify-full