golang 一些不错的环境变量管理包
joho/godotenv
ruby dotenv 库golang 的移植,功能还是比较强大的,同时支持编码加载变量
- 参考使用
package main
import (
"github.com/joho/godotenv"
"log"
"os"
)
func main() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
s3Bucket := os.Getenv("S3_BUCKET")
secretKey := os.Getenv("SECRET_KEY")
// now do something with s3 or whatever
}
a8m/envsubst
支持环境变量的替换
- 参考使用
package main
import (
"fmt"
"github.com/a8m/envsubst"
)
func main() {
input := "welcom $HOME"
str, err := envsubst.String(input)
// ...
buf, err := envsubst.Bytes([]byte(input))
// ...
buf, err := envsubst.ReadFile("filename")
}
Netflix/go-env
支持基于tag 的环境变量处理
- 参考使用
package main
import (
"log"
"time"
env "github.com/Netflix/go-env"
)
type Environment struct {
Home string `env:"HOME"`
Jenkins struct {
BuildId *string `env:"BUILD_ID"`
BuildNumber int `env:"BUILD_NUMBER"`
Ci bool `env:"CI"`
}
Node struct {
ConfigCache *string `env:"npm_config_cache,NPM_CONFIG_CACHE"`
}
Extras env.EnvSet
Duration time.Duration `env:"TYPE_DURATION"`
DefaultValue string `env:"MISSING_VAR,default=default_value"`
RequiredValue string `env:"IM_REQUIRED,required=true"`
}
func main() {
var environment Environment
es, err := env.UnmarshalFromEnviron(&environment)
if err != nil {
log.Fatal(err)
}
// Remaining environment variables.
environment.Extras = es
// ...
es, err = env.Marshal(environment)
if err != nil {
log.Fatal(err)
}
home := "/tmp/edgarl"
cs := env.ChangeSet{
"HOME": &home,
"BUILD_ID": nil,
"BUILD_NUMBER": nil,
}
es.Apply(cs)
environment = Environment{}
err = env.Unmarshal(es, &environment)
if err != nil {
log.Fatal(err)
}
environment.Extras = es
}
drone/envsubst
drone 团队出的,很不错
sethvargo/go-envconfig
同时也是基于tag的env 处理
- 参考代码
type MyConfig struct {
Port int `env:"PORT"`
Username string `env:"USERNAME"`
}
export PORT=5555
export USERNAME=yoyo
package main
import (
"context"
"log"
"github.com/sethvargo/go-envconfig"
)
func main() {
ctx := context.Background()
var c MyConfig
if err := envconfig.Process(ctx, &c); err != nil {
log.Fatal(err)
}
// c.Port = 5555
// c.Username = "yoyo"
}
joeshaw/envdecode
同样也是基于tag 的env 处理
- 参考代码
type Config struct {
Hostname string `env:"SERVER_HOSTNAME,default=localhost"`
Port uint16 `env:"SERVER_PORT,default=8080"`
AWS struct {
ID string `env:"AWS_ACCESS_KEY_ID"`
Secret string `env:"AWS_SECRET_ACCESS_KEY,required"`
SnsTopics []string `env:"AWS_SNS_TOPICS"`
}
Timeout time.Duration `env:"TIMEOUT,default=1m,strict"`
}
gobuffalo/envy
包含了更多的env set 以及加载文件处理,有好多新特性
参考资料
https://github.com/joho/godotenv
https://github.com/a8m/envsubst
https://github.com/Netflix/go-env
https://github.com/drone/envsubst
https://godoc.org/github.com/drone/envsubst
https://github.com/sethvargo/go-envconfig
https://github.com/joeshaw/envdecode
https://github.com/gobuffalo/envy