go-zero系列二: 配置文件加载

819 阅读1分钟

go-zero中加载配置文件使用方法是

签名方法
MustLoad(path string, v any, opts ...Option)
默认使用
conf.MustLoad(*configFile, &c)

如果需要使用加载项,添加conf.UseEnv()即可
conf.MustLoad(*configFile, &c,conf.UseEnv())

option 的相关如下

package conf

type (
   // Option defines the method to customize the config options.
   Option func(opt *options)

   options struct {
      env bool
   }
)

// UseEnv customizes the config to use environment variables.
func UseEnv() Option {
   return func(opt *options) {
      opt.env = true
   }
}

这个选项有什么用?

一般我们加载配置文件是直接会将所有的配置信息写入对应的配置文件,不能够从外界在接收参数,服务的启动配置只会依照我们的配置信息加载 加入这个配置选项,我们可以在控制台根据我们自己情况去动态配置配置文件中的各个参数

如何加载?如何使用的?

当我们使用配置项后

加载配置选项
var opt options
for _, o := range opts {
   o(&opt)
}
// 根据上面可以看到使用配置选项后,opt.env=true
if opt.env {
   return loader([]byte(os.ExpandEnv(string(content))), v)
}
这个方法接受外界参数然后对我们传入的字符串指定参数进行替换
os.ExpandEnv(string(content))
// ExpandEnv replaces ${var} or $var in the string according to the values
// of the current environment variables. References to undefined
// variables are replaced by the empty string.
func ExpandEnv(s string) string {
   return Expand(s, Getenv)
}

测试案例

user.yaml配置如下

Name: usercenter
Host: 0.0.0.0
Port: 1001
Log:
  ServiceName: $username
  Level: error

启动函数中打印替换后的日志服务名

var c config.Config
conf.MustLoad(*configFile, &c, conf.UseEnv())
fmt.Println("接受到的服务名:", c.Log.ServiceName)

启动服务

username=user-api go run usercenter.go -f etc/usercenter.yaml

输出结果

image.png