Go语言监控文件变化小程序.

前端之家收集整理的这篇文章主要介绍了Go语言监控文件变化小程序.前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package main

import (
	"log"

	"github.com/go-fsnotify/fsnotify"
)

func main() {
	watcher,err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}
	defer watcher.Close()
	done := make(chan bool)
	go func() {
		for {
			select {
			case event := <-watcher.Events:
				log.Println("event:",event)
				if event.Op&fsnotify.Write == fsnotify.Write {
					log.Println("modified file:",event.Name)
				}
			case err := <-watcher.Errors:
				log.Println("error:",err)
			}
		}
	}()

	err = watcher.Add("slog")
	if err != nil {
		log.Fatal(err)
	}
	<-done
}


package main

import (
	"github.com/howeyc/fsnotify"
	"log"
)

type monitor struct {
	watch *fsnotify.Watcher
}

func main() {
	M,err := NewMonitor()
	if err != nil {
		log.Println(err)
		return
	}
	M.Do()
	M.watch.Watch("../")
	select {}
}
func NewMonitor() (monitor,error) {
	Mon,err := fsnotify.NewWatcher()
	return monitor{Mon},err
}
func (self monitor) Do() {
	go func() {
		for {
			select {
			case w := <-self.watch.Event:
				log.Println(w)
				if w.IsModify() {
					continue
				}
				if w.IsDelete() {
					log.Println("文件删除.")
					continue
				}
				if w.IsRename() {
					w = <-self.watch.Event
					log.Println(w)
					self.watch.RemoveWatch(w.Name)
					log.Println(w.Name," 被重命名.")
				}
			case err := <-self.watch.Error:
				log.Fatalln(err)
			}
		}
	}()
}
原文链接:https://www.f2er.com/go/190181.html

猜你在找的Go相关文章