Sometimes, env can be very much, especially now many applications are placed in the Doker, many configurations are read through the environment variables, so I want to read the env can be associated with the Golang struct, such as:
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
You can do this by:
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//Re dis_version:3.2//redis_host:rdb//redis_port:6379//mysql_version:5.7//mysql_name:mysqldb//mysql_port:3306
If you do not want the struct's name as the env prefix, you can:
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 address.