main.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/fsnotify/fsnotify"
  6. "log"
  7. "os"
  8. "os/signal"
  9. "syscall"
  10. )
  11. func main() {
  12. ReadOSTemplate("C:\\Users\\lx\\GolandProjects\\demo3\\filewatch\\ipxe_template.json")
  13. go MonitorDirectory("C:\\Users\\lx\\GolandProjects\\demo3\\filewatch\\ipxe_template.json")
  14. interruptChan := make(chan os.Signal, 1)
  15. // 注册信号处理
  16. signal.Notify(interruptChan, os.Interrupt, syscall.SIGTERM)
  17. // 等待信号
  18. <-interruptChan
  19. }
  20. var OSScript = make(map[string]string)
  21. // MonitorDirectory 监视文件更改
  22. func MonitorDirectory(dirPath string) {
  23. watcher, err := fsnotify.NewWatcher()
  24. if err != nil {
  25. log.Fatal(err)
  26. }
  27. defer watcher.Close()
  28. done := make(chan bool)
  29. go func() {
  30. for {
  31. select {
  32. case event, ok := <-watcher.Events:
  33. if !ok {
  34. return
  35. }
  36. fmt.Println("event:", event)
  37. if event.Op&fsnotify.Write == fsnotify.Write {
  38. ReadOSTemplate(dirPath)
  39. }
  40. case err, ok := <-watcher.Errors:
  41. if !ok {
  42. return
  43. }
  44. fmt.Println("error:", err)
  45. }
  46. }
  47. }()
  48. // 添加需要监视的目录路径
  49. if err := addSubdirectories(watcher, dirPath); err != nil {
  50. log.Fatal(err)
  51. }
  52. <-done
  53. }
  54. func addSubdirectories(watcher *fsnotify.Watcher, dirPath string) error {
  55. if err := watcher.Add(dirPath); err != nil {
  56. return err
  57. }
  58. return nil
  59. }
  60. func ReadOSTemplate(dirPath string) {
  61. jsonFile, err := os.ReadFile(dirPath)
  62. if err != nil {
  63. log.Println("Error reading file:", err)
  64. return
  65. }
  66. err = json.Unmarshal(jsonFile, &OSScript)
  67. if err != nil {
  68. log.Println("Error reading file:", err)
  69. return
  70. }
  71. fmt.Println("OS Script:", OSScript)
  72. }