分享
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。
有时候,env会非常多,尤其是现在很多应用都放在doker里,很多配置都是通过环境变量读取,所以希望读取的env能与golang的struct能对应,比如:
```
CONFIG_APP=ENVAPP
CONFIG_DEBUG=1
CONFIG_HOSTS=192.168.0.1,127.0.0.1
CONFIG_TIMEOUT=5s
CONFIG_REDISVERSION=3.2
CONFIG_REDIS_HOST=rdb
CONFIG_REDIS_PORT=6379
CONFIG_MYSQL_HOST=mysqldb
CONFIG_MYSQL_PORT=3306
```
可以通过:
```golang
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=ENVAPP
DEBUG=1
HOSTS=192.168.0.1,127.0.0.1
TIMEOUT=5s
REDISVERSION=3.2
REDIS_HOST=rdb
REDIS_PORT=6379
MYSQL_HOST=mysqldb
MYSQL_PORT=3306
```
```
func main() {
cfg := new(config)
env.IgnorePrefix()
err := env.Fill(cfg)
...
}
```
[https://github.com/timest/env]("github.com/timest/env") 地址。
有疑问加站长微信联系(非本文作者))
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
关注微信4128 次点击 ∙ 1 赞
上一篇:Go 中 io 包的使用方法
添加一条新回复
(您需要 后才能回复 没有账号 ?)
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码` - 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传