1、config配置文件中新增全局变量
package configimport "github.com/zeromicro/go-zero/rest"type Config struct {rest.RestConfDB struct {DataSource string}Redis struct {Addr stringPassWord stringUserName string}Auth struct {AccessSecret stringAccessExpire int64}
}var GlobalConfig Config
2、main函数所在的入口文件为其赋值
package mainimport ("flag""fmt""go/application/basics/internal/config""go/application/basics/internal/handler""go/application/basics/internal/svc""github.com/zeromicro/go-zero/core/conf""github.com/zeromicro/go-zero/rest"
)var configFile = flag.String("f", "etc/basics-api.yaml", "the config file")func main() {flag.Parse()var c config.Configconf.MustLoad(*configFile, &c)config.GlobalConfig = cserver := rest.MustNewServer(c.RestConf)defer server.Stop()ctx := svc.NewServiceContext(c)handler.RegisterHandlers(server, ctx)fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)server.Start()
}
3、然后在想要使用的地方直接使用就可以了。
比如使用yaml中配置的JWT认证的key
config.GlobalConfig.Auth.AccessSecret