Skip to content

xmlgrg/envutils

 
 

Repository files navigation

envutils

go env utils

Usage

  1. 读取 struct 并将配置文件保存在 config.yml 中
func dump() {

	server := &Server{
		Address: "192.168.100.100",
	}

	config := &struct {
		Server *Server
	}{
		Server: server,
	}

	err := envutils.CallSetDefaults(config)
	if err != nil {
		panic(err)
	}

	b, err := envutils.Marshal(config, appname)
	if err != nil {
		panic(err)
	}
	_ = os.WriteFile(cfgfile, b, os.ModePerm)
}
  1. 查看保存文件
# cat config.yml 
AppName__Server_address: 192.168.100.100
AppName__Server_port: 80
  1. 从文件中读取配置
func read() {

	server := &Server{
		Address: "0.0.0.0",
	}

	config := &struct {
		Server *Server
	}{
		Server: server,
	}

	err := envutils.UnmarshalFile(config, appname, cfgfile)
	if err != nil {
		panic(err)
	}

	fmt.Println("addr=", config.Server.Address)
	fmt.Println("port=", config.Server.Port)
}
// addr= 192.168.100.100
// port= 80

Todo

  • 将结构体的 tag 转换为 config.yml
  • 从环境变量赋值结构体
  • 结构体字段支持 tag 名称

About

go env utils

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Go 100.0%