N
N
NOONE2018-08-03 00:41:57
go
NOONE, 2018-08-03 00:41:57

How to implement correctly on GO the functionality of tracking changes in a file?


The idea is to read the file after changes, transfer these changes to another function

func MusicFile()   {
  watcher, err := fsnotify.NewWatcher()
  if err != nil {
    log.Fatal(err)
  }
  defer watcher.Close()
  done := make(chan bool)
  go func() {
    fmt.Println("start")
    for {
      select {
      case event := <-watcher.Events:
        if event.Op&fsnotify.Write == fsnotify.Write {
          Parser.ParseMusicFile() -- Вызываю функцию парсинга если в канал записались данные о том что файл перезаписан 


      }
      case err := <-watcher.Errors:
        fmt.Println("error:", err)
      }
  }
  }()
  err = watcher.Add(Parser.ParsConfig().Directory)
  if err != nil {
    log.Fatal(err)
  }
  <-done

  }

I have a file parser
func ParseMusicFile() *MusicFile {
  reSong := regexp.MustCompile(`(?m)(^[^|]+(?:|))`)
  reArtist := regexp.MustCompile(`(?m)\|(.*)`)
  file, err := os.Open(ParsConfig().Directory)
  if err != nil {
    panic(err)
  }
  defer file.Close()
  MusicFile := &MusicFile{}
  scanner := bufio.NewScanner(file)
  for scanner.Scan() {
    if reSong.MatchString(scanner.Text()) { // Тут записывается результат найдено значение по регулярке или нет
      //*MusicFile.Song := reSong.MatchString(scanner.Text())
      MusicFile.Song = reSong.FindStringSubmatch(scanner.Text())[1]
    }else {
      MusicFile.Song = "null"
    }
    if reArtist.MatchString(scanner.Text()) { //Тут записывается результат найдено значение по регулярке или нет
      MusicFile.Artist = reArtist.FindStringSubmatch(scanner.Text())[1]
    }else {
      MusicFile.Artist = "null"
    }
  }

  return MusicFile
}

Парсер возвращает структуру

type MusicFile struct {
  Artist string
  Song   string
}

What’s the point, when the Watcher process starts, it hangs and reads changes in the file, the changes get there using third-party software, how can I properly organize the constant “backup” of changes using the Watcher function
Put on the right path, I guess changes using the parser as well need to be received through the channel? and to transfer already a pointer on this channel there where it is necessary?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question