Documentation ¶
Overview ¶
package filecache implements a simple file cache. A file cache can be created with either the NewDefaultCache() function to get a cache with the defaults set, or NewCache() to get a new cache with 0 values for everything; you will not be able to store items in this cache until the values are changed; specifically, at a minimum, you should change the MaxItems field to be greater than zero. Let's start with a basic example: cache := filecache.NewDefaultCache() cache.Start() readme, err := cache.ReadFile("README.md") if err != nil { fmt.Println("[!] couldn't read the README:", err.Error()) } else { fmt.Printf("[+] read %d bytes\n", len(readme)) }
You can transparently read and cache a file using RetrieveFile (and RetrieveFileString); if the file is not in the cache, it will be read from the file system and returned - the cache will start a background thread to cache the file. Similarly, the WriterFile method will write the file to the specified io.Writer. For example, you could create a FileServer function along the lines of
func FileServer(w http.ResponseWriter, r *http.Request) { path := r.URL.Path if len(path) > 1 { path = path[1:len(path)] } else { path = "." } err := cache.WriteFile(w, path) if err == nil { ServerError(w, r) } else if err == filecache.ItemIsDirectory { DirServer(w, r) } }
When cache.Start() is called, a goroutine is launched in the background that routinely checks the cache for expired items. The delay between runs is specified as the number of seconds given by cache.Every ("every cache.Every seconds, check for expired items"). There are three criteria used to determine whether an item in the cache should be expired; they are:
- Has the file been modified on disk? (The cache stores the last time of modification at the time of caching, and compares that to the file's current last modification time).
- Has the file been in the cache for longer than the maximum allowed time? This check can be disabled by setting the cache's ExpireItem field to 0; in this case, the cache will only expire items that have been modified since caching or that satisfy the next condition.
- Is the cache at capacity? When a file is being cached, a check is made to see if the cache is currently filled. If it is, the item that was last accessed the longest ago is expired and the new item takes its place. When loading items asynchronously, this check might miss the fact that the cache will be at capacity; the background scanner performs a check after its regular checks to ensure that the cache is not at capacity.
The background scanner can be disabled by setting cache.Every to 0; if so, cache expiration is only done when the cache is at capacity.
Once the cache is no longer needed, a call to cache.Stop() will close down the channels and signal the background scanner that it should stop.
Index ¶
- Constants
- Variables
- func HttpHandler(cache *FileCache) func(http.ResponseWriter, *http.Request)
- type FileCache
- func (cache *FileCache) Active() bool
- func (cache *FileCache) Cache(name string)
- func (cache *FileCache) CacheNow(name string) (err error)
- func (cache *FileCache) FileSize() (totalSize int64)
- func (cache *FileCache) GetItem(name string) (content []byte, ok bool)
- func (cache *FileCache) GetItemString(name string) (content string, ok bool)
- func (cache *FileCache) HttpWriteFile(w http.ResponseWriter, r *http.Request)
- func (cache *FileCache) InCache(name string) bool
- func (cache *FileCache) ReadFile(name string) (content []byte, err error)
- func (cache *FileCache) ReadFileString(name string) (content string, err error)
- func (cache *FileCache) Remove(name string) (ok bool, err error)
- func (cache *FileCache) Size() int
- func (cache *FileCache) Start() error
- func (cache *FileCache) Stop()
- func (cache *FileCache) StoredFiles() (fileList []string)
- func (cache *FileCache) WriteFile(w io.Writer, name string) (err error)
- func (cache *FileCache) WriteItem(w io.Writer, name string) (err error)
Constants ¶
const ( Kilobyte = 1024 //单位KB Megabyte = 1024 * 1024 //单位MB Gigabyte = 1024 * 1024 * 1024 //单位GB )
File size constants for use with FileCache.MaxSize. For example, cache.MaxSize = 64 * Megabyte
const VERSION = "1.0.2"
Variables ¶
var ( DefaultExpireItem int = 300 // 5 minutes DefaultMaxSize int64 = 16 * Megabyte DefaultMaxItems int = 32 DefaultEvery int = 60 // 1 minute )
var ( InvalidCacheItem = errors.New("invalid cache item") ItemIsDirectory = errors.New("can't cache a directory") ItemNotInCache = errors.New("item not in cache") ItemTooLarge = errors.New("item too large for cache") WriteIncomplete = errors.New("incomplete write of cache item") )
var NewCachePipeSize = 4
Mumber of items to buffer adding to the file cache. 配置缓存池的大小,当前正在往缓存中添加的文件数。
var SquelchItemNotInCache = true
Functions ¶
func HttpHandler ¶
func HttpHandler(cache *FileCache) func(http.ResponseWriter, *http.Request)
HttpHandler returns a valid HTTP handler for the given cache.
Types ¶
type FileCache ¶
type FileCache struct { MaxItems int // Maximum number of files to cache MaxSize int64 // Maximum file size to store ExpireItem int // Seconds a file should be cached for Every int // Run an expiration check Every seconds,每隔多少秒检查一次缓存是否到期 // contains filtered or unexported fields }
FileCache represents a cache in memory. An ExpireItem value of 0 means that items should not be expired based on time in memory. 代表内存中的缓存,属性ExpireItem值为0表示改项目在内存中没有过期时间限制。
func NewDefaultCache ¶
func NewDefaultCache() *FileCache
NewDefaultCache returns a new FileCache with sane defaults. 初试化一个默认的缓存
func (*FileCache) Active ¶
Active returns true if the cache has been started, and false otherwise. 判断缓存是否开启
func (*FileCache) Cache ¶
Cache will store the file named by 'name' to the cache. This function doesn't return anything as it passes the file onto the incoming pipe; the file will be cached asynchronously. Errors will not be returned.
func (*FileCache) FileSize ¶
FileSize returns the sum of the file sizes stored in the cache 返回缓存中的所有文件大小的总和
func (*FileCache) GetItem ¶
GetItem returns the content of the item and a bool if name is present. GetItem should be used when you are certain an object is in the cache, or if you want to use the cache only.
func (*FileCache) GetItemString ¶
GetItemString is the same as GetItem, except returning a string.
func (*FileCache) HttpWriteFile ¶
func (cache *FileCache) HttpWriteFile(w http.ResponseWriter, r *http.Request)
func (*FileCache) ReadFile ¶
ReadFile retrieves the file named by 'name'. If the file is not in the cache, load the file and cache the file in the background. If the file was not in the cache and the read was successful, the error ItemNotInCache is returned to indicate that the item was pulled from the filesystem and not the cache, unless the SquelchItemNotInCache global option is set; in that case, returns no error. 根据文件名获取缓存中的文件内容
func (*FileCache) ReadFileString ¶
ReadFileString is the same as ReadFile, except returning a string.
func (*FileCache) Remove ¶
RemoveItem immediately removes the item from the cache if it is present. It returns a boolean indicating whether anything was removed, and an error if an error has occurred.
func (*FileCache) Start ¶
Start activates the file cache; it will start up the background caching and automatic cache expiration goroutines and initialise the internal data structures. 启动缓存运行。它将创建两个goroutines(C中叫子线程),1负责在后台监听缓存请求,2负责自动删除过期的缓存。同事初始化结构体的数据。
func (*FileCache) Stop ¶
func (cache *FileCache) Stop()
Stop turns off the file cache. This closes the concurrent caching mechanism, destroys the cache, and the background scanner that it should stop. If there are any items or cache operations ongoing while Stop() is called, it is undefined how they will behave.
func (*FileCache) StoredFiles ¶
StoredFiles returns the list of files stored in the cache. 返回缓存中的所有文件列表