Skip to content

net/http: allow customization of FileServer's directory HTML and styling #47838

@rbucker

Description

@rbucker

go/src/net/http/fs.go

Lines 128 to 165 in e9e0d1e

func dirList(w ResponseWriter, r *Request, f File) {
// Prefer to use ReadDir instead of Readdir,
// because the former doesn't require calling
// Stat on every entry of a directory on Unix.
var dirs anyDirs
var err error
if d, ok := f.(fs.ReadDirFile); ok {
var list dirEntryDirs
list, err = d.ReadDir(-1)
dirs = list
} else {
var list fileInfoDirs
list, err = f.Readdir(-1)
dirs = list
}
if err != nil {
logf(r, "http: error reading directory: %v", err)
Error(w, "Error reading directory", StatusInternalServerError)
return
}
sort.Slice(dirs, func(i, j int) bool { return dirs.name(i) < dirs.name(j) })
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprintf(w, "<pre>\n")
for i, n := 0, dirs.len(); i < n; i++ {
name := dirs.name(i)
if dirs.isDir(i) {
name += "/"
}
// name may contain '?' or '#', which must be escaped to remain
// part of the URL path, and not indicate the start of a query
// string or fragment.
url := url.URL{Path: name}
fmt.Fprintf(w, "<a href=\"%s\">%s</a>\n", url.String(), htmlReplacer.Replace(name))
}
fmt.Fprintf(w, "</pre>\n")
}

The overarching purpose of the fileserver is to serve files in a safe way. But then it has this side effect of being able to generate a directory list. The directory list is a very basic PRE block with some A links. The code also sets the content-type. However, there is something missing.

  • is the HTML that it generates simply the smallest code possible?
  • is there a way to style that fragment either with a template or some CSS etc
  • since it's just a PRE block should I wrap the handler in a handler and then write a header, then call the handler, then write the footer
  • maybe there should be a callback instead of hardcoded
  • maybe there should be a template feature

At the very least please update the documentation to set the intent.

Metadata

Metadata

Assignees

No one assigned

    Labels

    FeatureRequestIssues asking for a new feature that does not need a proposal.FrozenDueToAgeNeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions