Go-Frame框架暂时不能链接nacos作为配置中心.
官方提供的set方法使用起来也比较麻烦.
但是可以剑走偏锋,在启动服务前做一次从nacos上拉取配置,
然后保存为本地配置文件,然后启动的时候指定配置文件的操作来解决问题
const filePath = "./config.toml"
type nacos struct {
dataId, groupId, configFilePath string
}
//初始化
func GetNacos(dataId, groupId string) (n *nacos, err error) {
n = &nacos{
dataId: dataId,
groupId: groupId,
}
err = n.getToFile()
return
}
//返回配置文件路径
func (n nacos) GetConfigFilePath() string {
if len(n.configFilePath) == 0 {
panic("nacos config to save local file is not found!")
}
return n.configFilePath
}
func (n *nacos) getToFile() (err error) {
//一个读取nacos内容的工具类 可以根据所需自行实现
context, _ := nacosUtil.InitToStr(n.dataId, n.groupId)
//创建文件
file, err := createFile(filePath)
//关闭
defer func(file *os.File) {
err := file.Close()
if err != nil {
panic("file close error")
}
}(file)
if file == nil {
panic("create or read file error")
}
//写入
writer := bufio.NewWriter(file)
_, err = writer.WriteString(context)
err = writer.Flush()
//返回
n.configFilePath = filePath
return
}
//创建文件
func createFile(path string) (file *os.File, err error) {
file, err = os.Create(path)
if err != nil {
panic("create file " + err.Error())
}
return
}
使用
func main() {
var (
args = os.Args
)
if len(args) > 4 {
NacosDataId = args[3]
NacosGroupId = args[4]
}
//获取nacos配置文件
nacosObj, _ := nacos.GetNacos(NacosDataId, NacosGroupId)
//指定配置文件路径
g.Cfg().GetString(nacosObj.GetConfigFilePath())
//其余初始化
boot.Init()
router.Init()
server := g.Server()
fmt.Println("url", g.Cfg().GetString("checkUrl.url"))
server.Run()
}