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

chore: minor performance improvements

This commit is contained in:
Ferdinand Mütsch 2021-12-20 16:41:50 +01:00
parent 80252ff701
commit e14f8c1463
3 changed files with 42 additions and 20 deletions

14
main.go
View File

@ -247,14 +247,12 @@ func main() {
// https://github.com/golang/go/issues/43431
embeddedStatic, _ := fs.Sub(staticFiles, "static")
static := conf.ChooseFS("static", embeddedStatic)
fileServer := gzipped.FileServer(fsutils.NewExistsHttpFs(
fsutils.ExistsFS{
Fs: fsutils.NeuteredFileSystem{
Fs: static,
},
}),
)
fileServer := gzipped.FileServer(fsutils.NewExistsHttpFS(
fsutils.NewExistsFS(
fsutils.NeuteredFileSystem{
FS: static,
}).WithCache(!config.IsDev()),
))
router.PathPrefix("/contribute.json").Handler(fileServer)
router.PathPrefix("/assets").Handler(fileServer)

View File

@ -1,35 +1,59 @@
package fs
import (
"github.com/patrickmn/go-cache"
"io/fs"
"net/http"
"strings"
)
func NewExistsFS(fs fs.FS) ExistsFS {
return ExistsFS{
FS: fs,
cache: cache.New(cache.NoExpiration, cache.NoExpiration),
}
}
type ExistsFS struct {
Fs fs.FS
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 {
_, err := fs.Stat(efs.Fs, name)
return err == nil
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) {
return efs.Fs.Open(name)
return efs.FS.Open(name)
}
// ---
type ExistsHttpFS struct {
Fs ExistsFS
ExistsFS
httpFs http.FileSystem
}
func NewExistsHttpFs(fs ExistsFS) ExistsHttpFS {
func NewExistsHttpFS(fs ExistsFS) ExistsHttpFS {
return ExistsHttpFS{
Fs: fs,
httpFs: http.FS(fs),
ExistsFS: fs,
httpFs: http.FS(fs),
}
}
@ -37,7 +61,7 @@ func (ehfs ExistsHttpFS) Exists(name string) bool {
if strings.HasPrefix(name, "/") {
name = name[1:]
}
return ehfs.Fs.Exists(name)
return ehfs.ExistsFS.Exists(name)
}
func (ehfs ExistsHttpFS) Open(name string) (http.File, error) {

View File

@ -8,11 +8,11 @@ import (
// https://www.alexedwards.net/blog/disable-http-fileserver-directory-listings
type NeuteredFileSystem struct {
Fs fs.FS
fs.FS
}
func (nfs NeuteredFileSystem) Open(path string) (fs.File, error) {
f, err := nfs.Fs.Open(path)
f, err := nfs.FS.Open(path)
if err != nil {
return nil, err
}
@ -20,7 +20,7 @@ func (nfs NeuteredFileSystem) Open(path string) (fs.File, error) {
s, err := f.Stat()
if s.IsDir() {
index := filepath.Join(path, "index.html")
if _, err := nfs.Fs.Open(index); err != nil {
if _, err := nfs.FS.Open(index); err != nil {
closeErr := f.Close()
if closeErr != nil {
return nil, closeErr