有時候,env會非常多,尤其是現在很多應用都放在doker裡,很多配置都是通過環境變數讀取,所以希望讀取的env能與golang的struct能對應,比如:
CONFIG_APP=ENVAPPCONFIG_DEBUG=1CONFIG_HOSTS=192.168.0.1,127.0.0.1CONFIG_TIMEOUT=5sCONFIG_REDISVERSION=3.2CONFIG_REDIS_HOST=rdbCONFIG_REDIS_PORT=6379CONFIG_MYSQL_HOST=mysqldbCONFIG_MYSQL_PORT=3306
可以通過:
import ( "fmt" "time" "os" "github.com/timest/env")type config struct { App string Port int `default:"8000"` IsDebug bool `env:"DEBUG"` Hosts []string `slice_sep:","` Timeout time.Duration Redis struct { Version string `sep:""` // no sep between `CONFIG` and `REDIS` Host string Port int } MySQL struct { Version string `default:"5.7"` Host string Port int }}func main() { cfg := new(config) err := env.Fill(cfg) if err != nil { panic(err) } fmt.Println("Home:", cfg.App) fmt.Println("Port:", cfg.Port) fmt.Println("IsDebug:", cfg.IsDebug) fmt.Println("Hosts:", cfg.Hosts, len(cfg.Hosts)) fmt.Println("Duration:", cfg.Timeout) fmt.Println("Redis_Version:", cfg.Redis.Version) fmt.Println("Redis_Host:", cfg.Redis.Host) fmt.Println("Redis_Port:", cfg.Redis.Port) fmt.Println("MySQL_Version:", cfg.MySQL.Version) fmt.Println("MySQL_Name:", cfg.MySQL.Host) fmt.Println("MySQL_port:", cfg.MySQL.Port)}// output:// Home: ENV APP// Port: 8000// IsDebug: true// Hosts: [192.168.0.1 127.0.0.1] 2// Duration: 5s// Redis_Version: 3.2// Redis_Host: rdb// Redis_Port: 6379// MySQL_Version: 5.7// MySQL_Name: mysqldb// MySQL_port: 3306
如果不希望struct的名字作為env的首碼,可以:
APP=ENVAPPDEBUG=1HOSTS=192.168.0.1,127.0.0.1TIMEOUT=5sREDISVERSION=3.2REDIS_HOST=rdbREDIS_PORT=6379MYSQL_HOST=mysqldbMYSQL_PORT=3306
func main() { cfg := new(config) env.IgnorePrefix() err := env.Fill(cfg) ...}
https://github.com/timest/env 地址。