1
0
mirror of https://github.com/muety/wakapi.git synced 2023-08-10 21:12:56 +03:00
wakapi/utils/fs/exists.go

70 lines
1.2 KiB
Go
Raw Normal View History

package fs
import (
2021-12-20 18:41:50 +03:00
"github.com/patrickmn/go-cache"
"io/fs"
"net/http"
"strings"
)
2021-12-20 18:41:50 +03:00
func NewExistsFS(fs fs.FS) ExistsFS {
return ExistsFS{
FS: fs,
cache: cache.New(cache.NoExpiration, cache.NoExpiration),
}
}
type ExistsFS struct {
2021-12-20 18:41:50 +03:00
fs.FS
UseCache bool
cache *cache.Cache
}
func (efs ExistsFS) WithCache(withCache bool) ExistsFS {
efs.UseCache = withCache
return efs
}
func (efs ExistsFS) Exists(name string) bool {
2021-12-20 18:41:50 +03:00
if efs.UseCache {
if result, ok := efs.cache.Get(name); ok {
return result.(bool)
}
}
_, err := fs.Stat(efs.FS, name)
result := err == nil
if efs.UseCache {
efs.cache.SetDefault(name, result)
}
return result
}
func (efs ExistsFS) Open(name string) (fs.File, error) {
2021-12-20 18:41:50 +03:00
return efs.FS.Open(name)
}
// ---
type ExistsHttpFS struct {
2021-12-20 18:41:50 +03:00
ExistsFS
httpFs http.FileSystem
}
2021-12-20 18:41:50 +03:00
func NewExistsHttpFS(fs ExistsFS) ExistsHttpFS {
return ExistsHttpFS{
2021-12-20 18:41:50 +03:00
ExistsFS: fs,
httpFs: http.FS(fs),
}
}
func (ehfs ExistsHttpFS) Exists(name string) bool {
if strings.HasPrefix(name, "/") {
name = name[1:]
}
2021-12-20 18:41:50 +03:00
return ehfs.ExistsFS.Exists(name)
}
func (ehfs ExistsHttpFS) Open(name string) (http.File, error) {
return ehfs.httpFs.Open(name)
}