add embed resource cache

This commit is contained in:
fancl 2023-06-19 16:13:34 +08:00
parent 9c47b20864
commit 302b90842b
2 changed files with 104 additions and 1 deletions

100
entry/http/file.go 100644
View File

@ -0,0 +1,100 @@
package http
import (
"io/fs"
"net/http"
"time"
)
type (
FS struct {
fs http.FileSystem
modtime time.Time
}
File struct {
fp http.File
modtime time.Time
}
FileInfo struct {
name string
size int64
mode fs.FileMode
isDir bool
modtime time.Time
}
)
func (fi *FileInfo) Name() string {
return fi.name
}
func (fi *FileInfo) Size() int64 {
return fi.size
}
func (fi *FileInfo) Mode() fs.FileMode {
return fi.mode
}
func (fi *FileInfo) ModTime() time.Time {
return fi.modtime
}
func (fi *FileInfo) IsDir() bool {
return fi.isDir
}
func (fi *FileInfo) Sys() any {
return nil
}
func (file *File) Close() error {
return file.fp.Close()
}
func (file *File) Read(p []byte) (n int, err error) {
return file.fp.Read(p)
}
func (file *File) Seek(offset int64, whence int) (int64, error) {
return file.fp.Seek(offset, whence)
}
func (file *File) Readdir(count int) ([]fs.FileInfo, error) {
return file.fp.Readdir(count)
}
func (file *File) Stat() (fs.FileInfo, error) {
fi, err := file.fp.Stat()
if err != nil {
return nil, err
}
return newFileInfo(fi, file.modtime), nil
}
func (fs *FS) Open(name string) (http.File, error) {
fp, err := fs.fs.Open(name)
if err != nil {
return nil, err
}
return &File{fp: fp, modtime: fs.modtime}, nil
}
func newFS(modtime time.Time, fs http.FileSystem) *FS {
return &FS{
fs: fs,
modtime: modtime,
}
}
func newFileInfo(fi fs.FileInfo, modtime time.Time) *FileInfo {
return &FileInfo{
name: fi.Name(),
size: fi.Size(),
mode: fi.Mode(),
isDir: fi.IsDir(),
modtime: modtime,
}
}

View File

@ -9,6 +9,7 @@ import (
"path" "path"
"strings" "strings"
"sync" "sync"
"time"
) )
var ( var (
@ -20,6 +21,7 @@ type Server struct {
serve *http.Server serve *http.Server
router *router.Router router *router.Router
middleware []Middleware middleware []Middleware
uptime time.Time
anyRequests map[string]http.Handler anyRequests map[string]http.Handler
} }
@ -115,7 +117,7 @@ func (svr *Server) Embed(prefix string, root string, embedFs embed.FS) {
filename = "/" + filename filename = "/" + filename
} }
ctx.Request().URL.Path = filename ctx.Request().URL.Path = filename
http.FileServer(httpFs).ServeHTTP(ctx.Response(), ctx.Request()) http.FileServer(newFS(svr.uptime, httpFs)).ServeHTTP(ctx.Response(), ctx.Request())
return return
}) })
} }
@ -190,6 +192,7 @@ func (svr *Server) Shutdown() (err error) {
func New(ctx context.Context) *Server { func New(ctx context.Context) *Server {
svr := &Server{ svr := &Server{
ctx: ctx, ctx: ctx,
uptime: time.Now(),
router: router.New(), router: router.New(),
anyRequests: make(map[string]http.Handler), anyRequests: make(map[string]http.Handler),
middleware: make([]Middleware, 0, 10), middleware: make([]Middleware, 0, 10),