fswatcher.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package xorm
  2. import (
  3. "strings"
  4. "github.com/fsnotify/fsnotify"
  5. )
  6. //start filesystem watcher
  7. func (engine *Engine) StartFSWatcher() error {
  8. var err error
  9. engine.watcher, err = fsnotify.NewWatcher()
  10. if err != nil {
  11. return err
  12. }
  13. go func() {
  14. for {
  15. select {
  16. case event := <-engine.watcher.Events:
  17. if event.Op&fsnotify.Write == fsnotify.Write {
  18. if strings.HasSuffix(event.Name, engine.SqlTemplate.Extension()) {
  19. err = engine.ReloadSqlTemplate(event.Name)
  20. if err != nil {
  21. engine.logger.Error(err)
  22. }
  23. }
  24. if strings.HasSuffix(event.Name, engine.SqlMap.Extension["xml"]) || strings.HasSuffix(event.Name, engine.SqlMap.Extension["json"]) || strings.HasSuffix(event.Name, engine.SqlMap.Extension["xsql"]) {
  25. err = engine.reloadSqlMap(event.Name)
  26. if err != nil {
  27. engine.logger.Error(err)
  28. }
  29. }
  30. }
  31. case err := <-engine.watcher.Errors:
  32. if err != nil {
  33. engine.logger.Error(err)
  34. }
  35. }
  36. }
  37. }()
  38. if engine.SqlMap.SqlMapRootDir != "" {
  39. err = engine.watcher.Add(engine.SqlMap.SqlMapRootDir)
  40. if err != nil {
  41. return err
  42. }
  43. }
  44. if engine.SqlTemplate.RootDir() != "" {
  45. err = engine.watcher.Add(engine.SqlTemplate.RootDir())
  46. if err != nil {
  47. return err
  48. }
  49. }
  50. return nil
  51. }
  52. //stop filesystem watcher
  53. func (engine *Engine) StopFSWatcher() error {
  54. return engine.watcher.Close()
  55. }