Golang Elegant Read environment variable env

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.