1.4 用os环境变量里获取值

1

package main

import (
	"log"
	"os"
)

func main() {
	connStr := os.Getenv("DB_CONN")
	log.Printf("Connection string: %s\n", 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.\n", 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

posted on 2018-03-17 22:05  cucy_to  阅读(435)  评论(0编辑  收藏  举报

导航