mirror of
https://github.com/Theodor-Springmann-Stiftung/kgpz_web.git
synced 2025-10-29 09:05:30 +00:00
Cache for file embedding + unsafe mebedding
This commit is contained in:
@@ -4,22 +4,53 @@ import (
|
|||||||
"html/template"
|
"html/template"
|
||||||
"io"
|
"io"
|
||||||
"io/fs"
|
"io/fs"
|
||||||
|
"sync"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TODO: this needs to be cached, FS reads are expensive
|
var embed_cache sync.Map
|
||||||
|
|
||||||
|
// INFO: We initialize the cache in both functions, which is only valid if both of these get
|
||||||
|
// called in the same context, eg. when creating a template engine.
|
||||||
func EmbedSafe(fs fs.FS) func(string) template.HTML {
|
func EmbedSafe(fs fs.FS) func(string) template.HTML {
|
||||||
|
embed_cache.Clear()
|
||||||
return func(path string) template.HTML {
|
return func(path string) template.HTML {
|
||||||
f, err := fs.Open(path)
|
val, err := getFileData(fs, path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return ""
|
return template.HTML("")
|
||||||
}
|
}
|
||||||
|
|
||||||
defer f.Close()
|
return template.HTML(val)
|
||||||
data, err := io.ReadAll(f)
|
|
||||||
if err != nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
return template.HTML(data)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func EmbedUnsafe(fs fs.FS) func(string) string {
|
||||||
|
embed_cache.Clear()
|
||||||
|
return func(path string) string {
|
||||||
|
val, err := getFileData(fs, path)
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
return string(val)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func getFileData(fs fs.FS, path string) ([]byte, error) {
|
||||||
|
if val, ok := embed_cache.Load(path); ok {
|
||||||
|
return val.([]byte), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
f, err := fs.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
|
||||||
|
data, err := io.ReadAll(f)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
embed_cache.Store(path, data)
|
||||||
|
return data, nil
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user