github.com/zhongdalu/gf@v1.0.0/g/os/gspath/gspath_cache.go (about) 1 // Copyright 2018 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/zhongdalu/gf. 6 7 // Package gspath implements file index and search for folders. 8 // 9 10 package gspath 11 12 import ( 13 "github.com/zhongdalu/gf/g/os/gfile" 14 "github.com/zhongdalu/gf/g/os/gfsnotify" 15 "github.com/zhongdalu/gf/g/text/gstr" 16 "runtime" 17 "strings" 18 ) 19 20 // 递归添加目录下的文件 21 func (sp *SPath) updateCacheByPath(path string) { 22 if sp.cache == nil { 23 return 24 } 25 sp.addToCache(path, path) 26 } 27 28 // 格式化name返回符合规范的缓存名称,分隔符号统一为'/',且前缀必须以'/'开头(类似HTTP URI). 29 func (sp *SPath) formatCacheName(name string) string { 30 if runtime.GOOS != "linux" { 31 name = gstr.Replace(name, "\\", "/") 32 } 33 return "/" + strings.Trim(name, "./") 34 } 35 36 // 根据path计算出对应的缓存name, dirPath为检索根目录路径 37 func (sp *SPath) nameFromPath(filePath, rootPath string) string { 38 name := gstr.Replace(filePath, rootPath, "") 39 name = sp.formatCacheName(name) 40 return name 41 } 42 43 // 按照一定数据结构生成缓存的数据项字符串 44 func (sp *SPath) makeCacheValue(filePath string, isDir bool) string { 45 if isDir { 46 return filePath + "_D_" 47 } 48 return filePath + "_F_" 49 } 50 51 // 按照一定数据结构解析数据项字符串 52 func (sp *SPath) parseCacheValue(value string) (filePath string, isDir bool) { 53 if value[len(value)-2 : len(value)-1][0] == 'F' { 54 return value[:len(value)-3], false 55 } 56 return value[:len(value)-3], true 57 } 58 59 // 添加path到缓存中(递归) 60 func (sp *SPath) addToCache(filePath, rootPath string) { 61 // 首先添加自身 62 idDir := gfile.IsDir(filePath) 63 sp.cache.SetIfNotExist(sp.nameFromPath(filePath, rootPath), sp.makeCacheValue(filePath, idDir)) 64 // 如果添加的是目录,那么需要递归添加 65 if idDir { 66 if files, err := gfile.ScanDir(filePath, "*", true); err == nil { 67 //fmt.Println("gspath add to cache:", filePath, files) 68 for _, path := range files { 69 sp.cache.SetIfNotExist(sp.nameFromPath(path, rootPath), sp.makeCacheValue(path, gfile.IsDir(path))) 70 } 71 } else { 72 //fmt.Errorf(err.Error()) 73 } 74 } 75 } 76 77 // 添加文件目录监控(递归),当目录下的文件有更新时,会同时更新缓存。 78 // 这里需要注意的点是,由于添加监听是递归添加的,那么假如删除一个目录,那么该目录下的文件(包括目录)也会产生一条删除事件,总共会产生N条事件。 79 func (sp *SPath) addMonitorByPath(path string) { 80 if sp.cache == nil { 81 return 82 } 83 _, _ = gfsnotify.Add(path, func(event *gfsnotify.Event) { 84 //glog.Debug(event.String()) 85 switch { 86 case event.IsRemove(): 87 sp.cache.Remove(sp.nameFromPath(event.Path, path)) 88 89 case event.IsRename(): 90 if !gfile.Exists(event.Path) { 91 sp.cache.Remove(sp.nameFromPath(event.Path, path)) 92 } 93 94 case event.IsCreate(): 95 sp.addToCache(event.Path, path) 96 } 97 }, true) 98 } 99 100 // 删除监听(递归) 101 func (sp *SPath) removeMonitorByPath(path string) { 102 if sp.cache == nil { 103 return 104 } 105 _ = gfsnotify.Remove(path) 106 }