Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sorting directories and files for static file serving #2715

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions middleware/static.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package middleware
import (
"errors"
"fmt"
"sort"
"html/template"
"net/http"
"net/url"
Expand Down Expand Up @@ -50,6 +51,12 @@ type StaticConfig struct {
Filesystem http.FileSystem `yaml:"-"`
}

// Used for sorting directories in listDir
type byName []os.FileInfo
func (s byName) Len() int { return len(s) }
func (s byName) Less(i, j int) bool { return s[i].Name() < s[j].Name() }
func (s byName) Swap(i, j int) { s[i], s[j] = s[j], s[i] }

const html = `
<!DOCTYPE html>
<html lang="en">
Expand Down Expand Up @@ -251,6 +258,9 @@ func listDir(t *template.Template, name string, dir http.File, res *echo.Respons
return
}

// Sort directories first
sort.Sort(byName(files))

// Create directory index
res.Header().Set(echo.HeaderContentType, echo.MIMETextHTMLCharsetUTF8)
data := struct {
Expand Down
Loading