take the directory's modtime into consideration when calculating lastModified

This commit is contained in:
WeidiDeng 2025-02-08 10:49:33 +08:00
parent 5e40605358
commit 560830c749
No known key found for this signature in database
GPG Key ID: 25F87CE1741EC7CD
2 changed files with 16 additions and 9 deletions

View File

@ -213,6 +213,11 @@ func (fsrv *FileServer) serveBrowse(fileSystem fs.FS, root, dirPath string, w ht
}
func (fsrv *FileServer) loadDirectoryContents(ctx context.Context, fileSystem fs.FS, dir fs.ReadDirFile, root, urlPath string, repl *caddy.Replacer) (*browseTemplateContext, error) {
// modTime for the directory itself
stat, err := dir.Stat()
if err != nil {
return nil, err
}
dirLimit := defaultDirEntryLimit
if fsrv.Browse.FileLimit != 0 {
dirLimit = fsrv.Browse.FileLimit
@ -225,7 +230,7 @@ func (fsrv *FileServer) loadDirectoryContents(ctx context.Context, fileSystem fs
// user can presumably browse "up" to parent folder if path is longer than "/"
canGoUp := len(urlPath) > 1
return fsrv.directoryListing(ctx, fileSystem, files, canGoUp, root, urlPath, repl), nil
return fsrv.directoryListing(ctx, fileSystem, stat.ModTime(), files, canGoUp, root, urlPath, repl), nil
}
// browseApplyQueryParams applies query parameters to the listing.

View File

@ -35,15 +35,16 @@ import (
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
)
func (fsrv *FileServer) directoryListing(ctx context.Context, fileSystem fs.FS, entries []fs.DirEntry, canGoUp bool, root, urlPath string, repl *caddy.Replacer) *browseTemplateContext {
func (fsrv *FileServer) directoryListing(ctx context.Context, fileSystem fs.FS, parentModTime time.Time, entries []fs.DirEntry, canGoUp bool, root, urlPath string, repl *caddy.Replacer) *browseTemplateContext {
filesToHide := fsrv.transformHidePaths(repl)
name, _ := url.PathUnescape(urlPath)
tplCtx := &browseTemplateContext{
Name: path.Base(name),
Path: urlPath,
CanGoUp: canGoUp,
Name: path.Base(name),
Path: urlPath,
CanGoUp: canGoUp,
lastModified: parentModTime,
}
for _, entry := range entries {
@ -66,10 +67,7 @@ func (fsrv *FileServer) directoryListing(ctx context.Context, fileSystem fs.FS,
}
// keep track of the most recently modified item in the listing
// this time is used for the Last-Modified header and comparing If-Modified-Since from client
// both are expected to be in UTC, so we convert to UTC here
// see: https://github.com/caddyserver/caddy/issues/6828
modTime := info.ModTime().UTC()
modTime := info.ModTime()
if tplCtx.lastModified.IsZero() || modTime.After(tplCtx.lastModified) {
tplCtx.lastModified = modTime
}
@ -134,6 +132,10 @@ func (fsrv *FileServer) directoryListing(ctx context.Context, fileSystem fs.FS,
})
}
// this time is used for the Last-Modified header and comparing If-Modified-Since from client
// both are expected to be in UTC, so we convert to UTC here
// see: https://github.com/caddyserver/caddy/issues/6828
tplCtx.lastModified = tplCtx.lastModified.UTC()
return tplCtx
}