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

75 lines
1.2 KiB
Go
Raw Normal View History

package fs
import (
2022-02-17 12:34:33 +03:00
lru "github.com/hashicorp/golang-lru"
"io/fs"
"net/http"
"strings"
)
2021-12-20 18:41:50 +03:00
func NewExistsFS(fs fs.FS) ExistsFS {
2022-02-17 12:34:33 +03:00
cache, err := lru.New(1 << 24)
if err != nil {
panic(err)
}
2021-12-20 18:41:50 +03:00
return ExistsFS{
FS: fs,
2022-02-17 12:34:33 +03:00
cache: cache,
2021-12-20 18:41:50 +03:00
}
}
type ExistsFS struct {
2021-12-20 18:41:50 +03:00
fs.FS
UseCache bool
2022-02-17 12:34:33 +03:00
cache *lru.Cache
2021-12-20 18:41:50 +03:00
}
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 {
2022-02-17 12:34:33 +03:00
efs.cache.Add(name, result)
2021-12-20 18:41:50 +03:00
}
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)
}