Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ReloadFiles方法在重载json格式的文件时会发生错误但toml正常 #112

Open
pya789 opened this issue Dec 10, 2022 · 0 comments
Open
Assignees
Labels
bug Something isn't working

Comments

@pya789
Copy link

pya789 commented Dec 10, 2022

// 监听配置文件热修改
func watchConfigFiles(cfg *config.Config) {
	// 开一个新线程防止主线程被卡住
	readyTask := new(sync.WaitGroup)
	readyTask.Add(1)
	go func() {
		watcher, err := fsnotify.NewWatcher()
		if err != nil {
			cliutil.Errorln(err.Error())
			return
		}
		defer watcher.Close()
		// 获取加载的配置文件
		files := cfg.LoadedFiles()
		if len(files) == 0 {
			cliutil.Errorln("未读取到配置文件")
			return
		}

		// 处理出错或通道关闭时的退出问题
		eventsTask := new(sync.WaitGroup)
		eventsTask.Add(1)
		go func() {
			for {
				select {
				case event, ok := <-watcher.Events:
					if !ok {
						eventsTask.Done()
						return
					}
					// 只有写入时才重新创建数据
					switch event.Op.String() {
					case "WRITE":
						// 重载数据
						if err := cfg.ReloadFiles(); err != nil {
							eventsTask.Done()
							cliutil.Errorf("重载%s数据出错,err:%s\n", event.Name, err.Error())
							return
						}
						cliutil.Infof("监听到%s变动\n", event.Name)
						fmt.Println(cfg.Data())
					case "REMOVE":
						eventsTask.Done()
						cliutil.Errorf("重载%s数据出错,err:文件被删除,请不要删除配置文件\n", event.Name)
						return
					default:
						cliutil.Infof("监听到%s变动 Op->%s\n", event.Name, event.Op.String())
					}
				case err, ok := <-watcher.Errors:
					if ok {
						cliutil.Errorln(err.Error())
					}
					if err != nil {
						cliutil.Errorln(err.Error())
					}
					eventsTask.Done()
					return
				}
			}
		}()
		// 加载文件的监听
		for _, path := range files {
			if err := watcher.Add(path); err != nil {
				cliutil.Errorln(err.Error())
			}
		}
		// 加载文件监听成功后释放创建监听的线程
		readyTask.Done()
		// 等待事件释放
		eventsTask.Wait()
	}()
	// 等待监听成功
	readyTask.Wait()
}

以上是监听代码

json文件使用的是github.com/gookit/config/v2/json这个驱动
toml文件使用的是github.com/gookit/config/v2/toml这个驱动

出错时报的错误:ReadMapCB: expect { or n, but found , error found in #0 byte of ...||..., bigger context ...||...

json格式的数据

{
  "app": {
    "name": "ceshi",
    "mode": "debug2"
  }
}

toml格式的数据

[app]
name = "ceshi"
mode = "debug"
@inhere inhere added the bug Something isn't working label Dec 11, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants