• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang v1.NewWatcher函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中gopkg/in/fsnotify/v1.NewWatcher函数的典型用法代码示例。如果您正苦于以下问题:Golang NewWatcher函数的具体用法?Golang NewWatcher怎么用?Golang NewWatcher使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了NewWatcher函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: main

func main() {
	flag.Parse()
	path = os.Getenv("PWD")
	if len(flag.Args()) > 1 {
		path = flag.Arg(1)
	}

	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}
	defer watcher.Close()

	done := make(chan bool)
	updates := make(chan Update)
	go WatcherEventLoop(watcher, updates, done)

	log.Println("Watching directory", path)
	err = filepath.Walk(path, AddWatch(watcher))
	if err != nil {
		log.Fatal(err)
	}

	listeners := make(chan Listener)
	go UpdateListeners(updates, listeners)

	http.HandleFunc("/", RootFunc)
	http.HandleFunc("/md/", PageFunc)
	http.HandleFunc("/github.css", CSSFunc(githubCss))
	http.Handle("/ws/", websocket.Handler(HandleListener(listeners)))
	http.ListenAndServe(fmt.Sprintf("%s:%s", *host, *port), nil)
}
开发者ID:abhijitmamarde,项目名称:livemd,代码行数:32,代码来源:livemd.go


示例2: AddPair

func (s *Syncer) AddPair(left, right string, config *PairConfig) error {

	lUri, err := uri.Parse(left)
	if err != nil {
		return err
	}
	rUri, err := uri.Parse(right)
	if err != nil {
		return err
	}
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		return err
	}

	p := &Pair{
		Left:     lUri,
		Right:    rUri,
		watcher:  watcher,
		progress: make(chan int64),
		handlers: make(map[fsnotify.Op][]OpHandler),
		syncer:   s,
		Config:   config,
	}
	s.Pairs = append(s.Pairs, p)
	go func(pair *Pair) {
		s.addPair <- pair
		fmt.Println("add pair", pair.Left.Uri())
	}(p)
	return nil
}
开发者ID:Felamande,项目名称:filesync.v2,代码行数:31,代码来源:sync.go


示例3: main

func main() {
	flag.Parse()

	w, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatalf("Error making watcher: %v", err)
	}

	dir, err := os.Getwd()
	if err != nil {
		log.Fatalf("Error getting wd: %v", err)
	}
	for ; !exists(path.Join(dir, ".git")); dir = path.Dir(dir) {
		if dir == "/" {
			log.Fatalf("Could not find git root")
		}
	}

	filepath.Walk(dir, makeWalker(w))

	wg.Add(1)
	populateOnce(dir)

	ch := make(chan struct{}, 100) // Buffered to ensure we can multiple-increment wg for pending writes
	go doPopulate(ch, dir)

	go watchFS(ch, w)
	fmt.Printf("Listening on port %d\n", *port)
	http.HandleFunc("/", serve)
	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *port), nil))

}
开发者ID:frankgerhardt,项目名称:matrix-doc,代码行数:32,代码来源:main.go


示例4: watchForFileChanges

func (s *SpecInfoGatherer) watchForFileChanges() {
	s.waitGroup.Add(1)

	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		logger.APILog.Error("Error creating fileWatcher: %s", err)
	}
	defer watcher.Close()

	done := make(chan bool)
	go func() {
		for {
			select {
			case event := <-watcher.Events:
				s.handleEvent(event, watcher)
			case err := <-watcher.Errors:
				logger.APILog.Error("Error event while watching specs", err)
			}
		}
	}()

	allDirsToWatch := make([]string, 0)

	specDir := filepath.Join(config.ProjectRoot, common.SpecsDirectoryName)
	allDirsToWatch = append(allDirsToWatch, specDir)
	allDirsToWatch = append(allDirsToWatch, util.FindAllNestedDirs(specDir)...)

	for _, dir := range allDirsToWatch {
		s.addDirToFileWatcher(watcher, dir)
	}
	s.waitGroup.Done()
	<-done
}
开发者ID:0-T-0,项目名称:gauge,代码行数:33,代码来源:specDetails.go


示例5: NewWatcher

// NewWatcher create watcher
func NewWatcher(dirs []string) (*Watcher, error) {
	// w
	w, err := fs.NewWatcher()
	if err != nil {
		return nil, err
	}

	// listen
	log.Println("[umon]", "Watcher: watch dirs", dirs)
	for _, dir := range dirs {
		filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
			if info == nil {
				return err
			}
			if !info.IsDir() {
				return nil
			}
			w.Add(path)
			return nil
		})
	}

	// ok
	return &Watcher{
		w:    w,
		exit: make(ChanExit, 1),
	}, nil
}
开发者ID:ot24net,项目名称:umon,代码行数:29,代码来源:umon.go


示例6: NewNotifier

func NewNotifier(config *Config) (*Notifier, error) {
	w, err := fsnotify.NewWatcher()
	if err != nil {
		return &Notifier{}, err
	}

	return &Notifier{c: config, w: w}, nil
}
开发者ID:nickwales,项目名称:proxym,代码行数:8,代码来源:file.go


示例7: TestWatchWrite

func TestWatchWrite(t *testing.T) {

	sandbox(func(tmpDir string) {
		var err error
		var watcher *fsnotify.Watcher

		if watcher, err = fsnotify.NewWatcher(); err != nil {
			t.Fatal(fmt.Errorf("failed to create watcher: %s", err))
		}
		defer watcher.Close()

		result := make(chan interface{})
		timeout := time.Millisecond * 200
		go func() {
			for {
				select {
				case event := <-watcher.Events:
					result <- event.Op
				case err := <-watcher.Errors:
					result <- err
				case <-time.After(timeout):
					result <- fmt.Errorf("event did not occur within timeout of %v", timeout)
				}
			}
		}()

		// create file before adding to watcher
		var f *os.File
		if f, err = os.Create(filepath.Join(tmpDir, "a.txt")); err != nil {
			t.Fatal(err)
		}
		defer f.Close()

		if err = watcher.Add(tmpDir); err != nil {
			t.Fatal(err)
		}

		// perform write
		f.Write([]byte("hello"))

		// wait on result
		res := <-result

		expect := fsnotify.Write
		switch res.(type) {
		case fsnotify.Op:
			if res != fsnotify.Write {
				t.Errorf("expect: %v, result: %v", expect, res)
			}
		case error:
			t.Error(res)
		default:
			t.Fatal("unexpected response")
		}
	})

}
开发者ID:pfeilbr,项目名称:go-examples,代码行数:57,代码来源:basic_test.go


示例8: main

func main() {
	if *hotReload {
		// set up file watcher
		log.Printf("setting up file watcher for %s\n", *hooksFilePath)

		var err error

		watcher, err = fsnotify.NewWatcher()
		if err != nil {
			log.Fatal("error creating file watcher instance", err)
		}

		defer watcher.Close()

		go watchForFileChange()

		err = watcher.Add(*hooksFilePath)
		if err != nil {
			log.Fatal("error adding hooks file to the watcher", err)
		}
	}

	l := negroni.NewLogger()
	l.Logger = log.New(os.Stdout, "[webhook] ", log.Ldate|log.Ltime)

	negroniRecovery := &negroni.Recovery{
		Logger:     l.Logger,
		PrintStack: true,
		StackAll:   false,
		StackSize:  1024 * 8,
	}

	n := negroni.New(negroniRecovery, l)

	router := mux.NewRouter()

	var hooksURL string

	if *hooksURLPrefix == "" {
		hooksURL = "/{id}"
	} else {
		hooksURL = "/" + *hooksURLPrefix + "/{id}"
	}

	router.HandleFunc(hooksURL, hookHandler)

	n.UseHandler(router)

	if *secure {
		log.Printf("starting secure (https) webhook on %s:%d", *ip, *port)
		log.Fatal(http.ListenAndServeTLS(fmt.Sprintf("%s:%d", *ip, *port), *cert, *key, n))
	} else {
		log.Printf("starting insecure (http) webhook on %s:%d", *ip, *port)
		log.Fatal(http.ListenAndServe(fmt.Sprintf("%s:%d", *ip, *port), n))
	}

}
开发者ID:jszalkowski,项目名称:webhook,代码行数:57,代码来源:webhook_windows.go


示例9: watchFile

// watchFile assigns a new fsnotify watcher to the file if possible.
// It it watches for any signals that lead to file change, and responds accordingly.
func (t *Tail) watchFile(newFile bool) error {
	if t.watcher != nil {
		t.watcher.Close()
	}

	var err error
	t.watcher, err = fsnotify.NewWatcher()
	if err != nil {
		return err
	}

	err = t.watcher.Add(t.fname)
	if err != nil {
		return err
	}

	go func() {
		// Start reading at the beginning of the file if new
		if newFile {
			t.readLines()
		}

		for {
			closed := false
			select {
			case evt, ok := <-t.watcher.Events:
				// Exit if the channel is closed
				if !ok {
					closed = true
					break
				}
				if evt.Op&(fsnotify.Create|fsnotify.Rename|fsnotify.Remove) != 0 {
					if err = t.openAndWatch(); err != nil {
						log.Fatalln("[FATA] open and watch failed: ", err)
					}
				}
				if evt.Op&fsnotify.Write == fsnotify.Write {
					t.readLines()
				}
			case err, ok := <-t.watcher.Errors:
				// Exit if the channel is closed
				if !ok {
					closed = true
					break
				}
				if err != nil {
					log.Println("[WARN] watcher error: ", err)
				}
			}
			if closed {
				break
			}
		}
	}()

	return nil
}
开发者ID:bcandrea,项目名称:gotail,代码行数:59,代码来源:gotail.go


示例10: startWatch

func startWatch(watches *services.ServiceWatch, cfg services.OperationConfig) (*fsnotify.Watcher, error) {
	fmt.Printf("Watching %v paths for service %v\n", len(watches.IncludedPaths), watches.Service.GetName())
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		return nil, errors.WithStack(err)
	}

	go func() {
		for {
			select {
			case event := <-watcher.Events:
				if event.Op&fsnotify.Write == fsnotify.Write {
					fmt.Printf("File edited: %v\n", event.Name)

					var wasExcluded bool
					for _, excluded := range watches.ExcludedPaths {
						if strings.HasPrefix(event.Name, excluded) {
							fmt.Println("File is under excluded path:", excluded)
							wasExcluded = true
							break
						}
					}

					if wasExcluded {
						continue
					}
					fmt.Printf("Rebuilding %v\n", watches.Service.GetName())
					err = rebuildService(watches.Service, cfg)
					if err != nil {
						fmt.Printf("Could not rebuild %v: %v\n", watches.Service.GetName(), err)
					}
				}

			case err := <-watcher.Errors:
				if err != nil {
					log.Println("error:", err)
				}
			}
		}
	}()

	for _, dir := range watches.IncludedPaths {
		err = watcher.Add(dir)
		if err != nil {
			watcher.Close()
			return nil, errors.WithStack(err)
		}
	}
	return watcher, nil
}
开发者ID:yext,项目名称:edward,代码行数:50,代码来源:watch.go


示例11: watchFFDB

func watchFFDB(fxLocation string, lastLogData []byte, errorLog *os.File) {
	fxPlaces := fxLocation + "places.sqlite"

	fxPlacesDB, err := OpenAndCheckSQLiteDB(fxPlaces)
	if err != nil {
		SomethingBroke(errorLog, err, "Did not connect to Firefox database")
	} else {
		Notify(errorLog, "Database "+fxPlaces+" opened.")
	}

	dbWatcher, err := fsnotify.NewWatcher()
	if err != nil {
		SomethingBroke(errorLog, err, "White Walkers got to the new Watcher before he could be assigned.")
	} else {
		Notify(errorLog, fmt.Sprintf("Watcher assigned to %s", fxPlaces))
	}
	defer dbWatcher.Close()
	dbWatcher.Add(fxPlaces)

	var lastLog Visit

	//This whole section exists for persistence; after logging is initiated, only writes are made, no reads.
	//By keeping a record of the last entry, we don't end up with duplicate data being sent after restart.

	err2 := json.Unmarshal([]byte(lastLogData), &lastLog)
	Notify(errorLog, "Initiating; unmarshaled last log")
	if err2 != nil {
		SomethingBroke(errorLog, err2)
	}

	var (
		lastDate int
		lastURL  string
	)

	lastDate = lastLog.Timestamp
	lastURL = lastLog.URL

	for {
		select {
		case event := <-dbWatcher.Events:
			if event.Op&fsnotify.Write == fsnotify.Write {
				lastDate, lastURL = catchDBChanges(fxPlacesDB, lastDate, lastURL, errorLog)
			}
		case err := <-dbWatcher.Errors:
			SomethingBroke(errorLog, err, "dbWatcher encountered an error and gave up in disgust")
		}
	}
}
开发者ID:Xymist,项目名称:kiosk-admin,代码行数:49,代码来源:watch_upload.go


示例12: NewWatcher

func NewWatcher() (*Watcher, error) {
	var w Watcher
	var err error

	w.watcher, err = fsnotify.NewWatcher()
	if err != nil {
		return nil, err
	}

	w.Events = make(chan fsnotify.Event)
	w.Errors = make(chan error)
	w.quit = make(chan bool)

	go w.watch()

	return &w, err
}
开发者ID:jackc,项目名称:react2fs,代码行数:17,代码来源:watcher.go


示例13: MustRegisterWatcher

// MustRegisterWatcher creates a new Watcher and starts listening
// given folders
func MustRegisterWatcher(params *Params) *Watcher {

	w := &Watcher{
		update:  make(chan bool),
		rootdir: params.Get("watch"),
	}

	var err error
	w.watcher, err = fsnotify.NewWatcher()
	if err != nil {
		log.Fatalf("Could not register watcher: %s", err)
	}

	// add watched paths
	w.watchFolders()

	return w
}
开发者ID:rwuebker,项目名称:go-watcher,代码行数:20,代码来源:watch.go


示例14: FollowFile

func FollowFile(path string, cfg *tf.TfcatConfig) {

	if !FileExists(path) {
		fmt.Fprintf(os.Stderr, "input file '%s' does not exist.\n", path)
		os.Exit(1)
	}

	watcher, err := fsnotify.NewWatcher()
	panicOn(err)
	defer watcher.Close()

	f, err := os.Open(path)
	panicOn(err)
	// move to end for tailing
	_, err = f.Seek(0, 2)
	panicOn(err)

	err = watcher.Add(path)
	panicOn(err)

	fr := tf.NewFrameReader(f, 1024*1024)

	var frame tf.Frame

	i := int64(1)
nextFrame:
	for {
		_, _, err, _ = fr.NextFrame(&frame)
		if err != nil {
			if err == io.EOF {
				select {
				case event := <-watcher.Events:
					if event.Op&fsnotify.Write == fsnotify.Write {
						continue nextFrame
					}
				}
			}
			fmt.Fprintf(os.Stderr, "tfcat error from fr.NextFrame(): '%v'\n", err)
			os.Exit(1)
		}
		frame.DisplayFrame(os.Stdout, i, cfg.PrettyPrint, cfg.SkipPayload, cfg.Rreadable)
		i++
	}
}
开发者ID:glycerine,项目名称:tmframe,代码行数:44,代码来源:tfcat.go


示例15: NewTilesetIndex

// NewTilesetIndex creates a new tileset index, but does not read the tile tilesets from disk
func NewTilesetIndex(mbtilesDir string) (tsi *TilesetIndex, err error) {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		return
	}
	watcher.Add(mbtilesDir)
	cache, err := InitTileCache(filepath.Join(mbtilesDir, CacheName))
	if err != nil {
		return
	}
	tsi = &TilesetIndex{
		Path:     mbtilesDir,
		Tilesets: make(map[string]*mbtiles.Tileset),
		Events:   make(chan TsEvent),
		watcher:  watcher,
		cache:    cache,
	}
	return
}
开发者ID:buckhx,项目名称:diglet,代码行数:20,代码来源:tileset.go


示例16: WatchConfig

func (rs *RestartableServer) WatchConfig() {
	w, err := fsnotify.NewWatcher()
	if err != nil {
		glog.Fatalf("Failed to create watcher: %s", err)
	}
	defer w.Close()

	stopSignals := make(chan os.Signal, 1)
	signal.Notify(stopSignals, syscall.SIGTERM, syscall.SIGINT)

	err = w.Add(rs.configFile)
	watching, needRestart := (err == nil), false
	for {
		select {
		case <-time.After(1 * time.Second):
			if !watching {
				err = w.Add(rs.configFile)
				if err != nil {
					glog.Errorf("Failed to set up config watcher: %s", err)
				} else {
					watching, needRestart = true, true
				}
			} else if needRestart {
				rs.MaybeRestart()
				needRestart = false
			}
		case ev := <-w.Events:
			if ev.Op == fsnotify.Remove {
				glog.Warningf("Config file disappeared, serving continues")
				w.Remove(rs.configFile)
				watching, needRestart = false, false
			} else if ev.Op == fsnotify.Write {
				needRestart = true
			}
		case s := <-stopSignals:
			signal.Stop(stopSignals)
			glog.Infof("Signal: %s", s)
			rs.hs.Stop()
			rs.authServer.Stop()
			glog.Exitf("Exiting")
		}
	}
}
开发者ID:arloesol,项目名称:docker_auth,代码行数:43,代码来源:main.go


示例17: newPair

func (s *Syncer) newPair(config settings.SyncConfig, source, target string, IgnoreRules []string) error {
	lURI, err := uri.Parse(source)
	if err != nil {
		return err
	}
	rURI, err := uri.Parse(target)
	if err != nil {
		return err
	}
	var m = make(map[string]bool, 6)
	for _, ignore := range IgnoreRules {
		m[ignore] = true
	}

	pair := &SyncPair{
		Left:      lURI,
		Right:     rURI,
		Config:    config,
		IgnoreMap: m,
	}
	fmt.Println("s.ignore", IgnoreRules)
	pair.watcher, err = fsnotify.NewWatcher()
	if err != nil {
		return err
	}

	if !pair.Left.IsAbs() || !pair.Right.IsAbs() {
		err = PairNotValidError{pair.Left.Abs(), pair.Right.Abs(), "Pair Uris not absolute"}
		return err
	}
	if !pair.Left.Exist() {
		err = PairNotValidError{pair.Left.Abs(), pair.Right.Abs(), "Res of left Uri not exist"}
		return err
	}

	s.SyncPairs = append(s.SyncPairs, pair)
	s.PairMap[pair.Left.Uri()] = pair.Right.Uri()
	go func(p *SyncPair) {
		p.BeginWatch()
	}(pair)

	return nil
}
开发者ID:Felamande,项目名称:filesync,代码行数:43,代码来源:syncer.go


示例18: getWatcher

func getWatcher(rootPaths []string) (*fsnotify.Watcher, error) {

	watchPaths, err := getWatchPaths(rootPaths)
	if err != nil {
		return nil, err
	}

	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		return nil, err
	}

	for _, path := range watchPaths {
		if err := watcher.Add(path); err != nil {
			return nil, err
		}
	}

	return watcher, nil
}
开发者ID:tsandall,项目名称:opa,代码行数:20,代码来源:runtime.go


示例19: NewBuilder

func NewBuilder(c config) (*Bob, error) {
	w, err := fsn.NewWatcher()
	if err != nil {
		return nil, err
	}

	cmds := make([][]string, len(c.Script))
	for i, s := range c.Script {
		cmds[i] = strings.Split(s, " ")
	}

	return &Bob{
		w:            w,
		done:         make(chan struct{}),
		watching:     map[string]struct{}{},
		cmds:         cmds,
		ignoredItems: c.IgnoredItems,
		verbose:      c.Verbose,
	}, nil
}
开发者ID:zabawaba99,项目名称:snag,代码行数:20,代码来源:builder.go


示例20: NewBuilder

func NewBuilder(c config) (*Bob, error) {
	w, err := fsn.NewWatcher()
	if err != nil {
		return nil, err
	}

	parseCmd := func(cmd string) (c []string) {
		s := bufio.NewScanner(strings.NewReader(cmd))
		s.Split(splitFunc)
		for s.Scan() {
			c = append(c, s.Text())
		}

		// check for environment variables inside script
		if strings.Contains(cmd, "$$") {
			replaceEnv(c)
		}
		return c
	}

	buildCmds := make([][]string, len(c.Build))
	for i, s := range c.Build {
		buildCmds[i] = parseCmd(s)
	}

	runCmds := make([][]string, len(c.Run))
	for i, s := range c.Run {
		runCmds[i] = parseCmd(s)
	}

	return &Bob{
		w:            w,
		done:         make(chan struct{}),
		watching:     map[string]struct{}{},
		buildCmds:    buildCmds,
		runCmds:      runCmds,
		depWarning:   c.DepWarnning,
		ignoredItems: c.IgnoredItems,
		verbose:      c.Verbose,
	}, nil
}
开发者ID:Tonkpils,项目名称:snag,代码行数:41,代码来源:builder.go



注:本文中的gopkg/in/fsnotify/v1.NewWatcher函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang v1.Watcher类代码示例发布时间:2022-05-28
下一篇:
Golang v2.Table函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap