golang监听文件变化的实例
作者:雪东~ 时间:2024-05-08 10:24:34
废话不多说,直接上官网demo
package main
import (
"log"
"github.com/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, ok := <-watcher.Events:
if !ok {
return
}
log.Println("event:", event)
if event.Op&fsnotify.Write == fsnotify.Write {
log.Println("modified file:", event.Name)
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Println("error:", err)
}
}
}()
err = watcher.Add("/tmp/foo")
if err != nil {
log.Fatal(err)
}
<-done
}
补充:golang监控文件变化,git自动提交代码
代码如下:
如果文件有变动,且10分钟内,没有再次变动,则提交代码
package main
import (
"fmt"
_ "fmt"
"github.com/fsnotify/fsnotify"
"log"
"os"
"os/exec"
"path/filepath"
"time"
)
//if the conditions are met, execute the shell script
func execCmd() {
cmd := exec.Command("/root/nfs_bak_pro/nfs.git.sh")
err := cmd.Run()
if err != nil {
fmt.Println("Execute Command failed:" + err.Error())
return
}
fmt.Println("Execute Command finished.")
}
//handle folder files changed event
func watchFiles(watcher *fsnotify.Watcher, ch chan int64) {
for {
select {
case ev := <-watcher.Events: {
isNotify := false
if ev.Op & fsnotify.Create == fsnotify.Create {
log.Println("create : ", ev.Name)
isNotify = true
file, err := os.Stat(ev.Name)
if err == nil && file.IsDir() {
watcher.Add(ev.Name)
fmt.Println("add watch : ", ev.Name)
}
}
if ev.Op & fsnotify.Remove == fsnotify.Remove {
log.Println("delete : ", ev.Name)
isNotify = true
err := watcher.Remove(ev.Name)
fmt.Printf("remove watch: %s, err: %v\n", ev.Name, err)
}
if ev.Op & fsnotify.Rename == fsnotify.Rename {
log.Println("rename : ", ev.Name)
if "" != ev.Name {
isNotify = true
err := watcher.Remove(ev.Name)
fmt.Printf("remove watch: %s, err: %v\n", ev.Name, err)
}
}
if isNotify {
ch <- time.Now().Unix()
}
}
case err := <-watcher.Errors: {
log.Println("watcher error : ", err)
return
}
}
}
}
//if folder event met, execute the shell script after 10minutes
func watchTime(ch chan int64) {
var timer *time.Timer
for {
select {
case <- ch:{
if nil != timer {
log.Printf("reset timer")
timer.Stop()
}
timer = time.NewTimer(10 * 60 * time.Second)
go func() {
<-timer.C
execCmd()
}()
}
}
}
}
//watch the folder and sub folders
func WatchDir(watcher *fsnotify.Watcher, dir string) {
filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
path, err := filepath.Abs(path)
if err != nil {
return err
}
err = watcher.Add(path)
if err != nil {
return err
}
}
return nil
})
}
func main() {
notifyCh := make(chan int64)
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
defer watcher.Close()
WatchDir(watcher, "/data/nfs")
go watchFiles(watcher, notifyCh)
go watchTime(notifyCh)
select {}
}
shell 脚本如下
#!/bin/bash
cd /root/nfs_bak_pro/nfs.git
log_file=/root/nfs_bak_pro/nfs_git_`date +"%Y%m%d"`.log
git add --all . >> $log_file
git commit -a -m "`date +"%Y-%m-%d %H:%M:%S"`" >> $log_file
git push origin master >> $log_file
以上为个人经验,希望能给大家一个参考,也希望大家多多支持asp之家。如有错误或未考虑完全的地方,望不吝赐教。
来源:https://blog.csdn.net/weixin_39998006/article/details/106854551
标签:golang,监听,文件
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python实现简易聊天室(Linux终端)
2022-03-30 09:44:01
python实现猜拳游戏项目
2023-02-25 15:15:30
Python实现邮件发送功能的示例详解
2022-08-18 13:15:43
![](https://img.aspxhome.com/file/2023/7/123807_0s.png)
关于 SQL Server ErrorLog 错误日志说明
2024-01-19 23:57:03
python dataframe向下向上填充,fillna和ffill的方法
2021-11-07 18:16:47
网站发布后Bootstrap框架引用woff字体无法正常显示的解决方法
2023-08-13 00:26:58
Python自定义sorted排序实现方法详解
2022-08-03 05:40:02
在JavaScript中对HTML进行反转义详解
2024-05-02 16:21:19
Windows 8.1 64bit下搭建 Scrapy 0.22 环境
2023-07-23 12:51:08
![](https://img.aspxhome.com/file/2023/7/64327_0s.png)
原生js实现放大镜组件
2024-05-11 09:06:05
![](https://img.aspxhome.com/file/2023/7/127187_0s.jpg)
关于PyQt5中QtGui.QImage图片显示问题解析
2022-05-17 19:59:12
![](https://img.aspxhome.com/file/2023/4/111884_0s.png)
基于Python实现图片一键切割九宫格的工具
2022-07-05 00:22:31
asp中将有双引号标题入库的方法
2023-07-09 15:24:56
Yolov5训练意外中断后如何接续训练详解
2022-05-14 00:16:51
![](https://img.aspxhome.com/file/2023/1/103001_0s.png)
详解pyenv下使用python matplotlib模块的问题解决
2023-08-08 20:25:01
![](https://img.aspxhome.com/file/2023/6/104946_0s.png)
Python编写条件分支代码方法
2021-08-16 12:31:17
JavaScript事件委托技术实例分析
2023-07-01 01:18:23
javascript实现自动输出文本(打字特效)
2024-02-25 18:25:14
Python使用SQLite和Excel操作进行数据分析
2023-11-27 22:32:28
从零开始做一个pagination分页组件
2024-04-29 13:25:13
![](https://img.aspxhome.com/file/2023/7/132667_0s.jpg)