1、config配置文件中新增全局变量
package config
import "github.com/zeromicro/go-zero/rest"
type Config struct {
rest.RestConf
DB struct {
DataSource string
}
Redis struct {
Addr string
PassWord string
UserName string
}
Auth struct {
AccessSecret string
AccessExpire int64
}
}
var GlobalConfig Config
2、main函数所在的入口文件为其赋值
package main
import (
"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.Config
conf.MustLoad(*configFile, &c)
config.GlobalConfig = c
server := 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