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

Fix error in createStaticHandler when handling directories and index.html #4073

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
13 changes: 0 additions & 13 deletions routergroup.go
Original file line number Diff line number Diff line change
Expand Up @@ -221,19 +221,6 @@ func (group *RouterGroup) createStaticHandler(relativePath string, fs http.FileS
if _, noListing := fs.(*OnlyFilesFS); noListing {
c.Writer.WriteHeader(http.StatusNotFound)
}

file := c.Param("filepath")
// Check if file exists and/or if we have permission to access it
f, err := fs.Open(file)
if err != nil {
c.Writer.WriteHeader(http.StatusNotFound)
c.handlers = group.engine.noRoute
// Reset index
c.index = -1
return

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ого// fs.go
func serveFile(w ResponseWriter, r *Request, fs FileSystem, name string, redirect bool) {
const indexPage = "/index.html"

// redirect .../index.html to .../
// can't use Redirect() because that would make the path absolute,
// which would be a problem running under StripPrefix
if strings.HasSuffix(r.URL.Path, indexPage) {
	localRedirect(w, r, "./")
	return
}
f, err := fs.Open(name)
if err != nil {
	msg, code := toHTTPError(err)
	Error(w, msg, code)
	return
}
defer f.Close()

d, err := f.Stat()
if err != nil {
	msg, code := toHTTPError(err)
	Error(w, msg, code)
	return
}

if redirect {
	// redirect to canonical path: / at end of directory url
	// r.URL.Path always begins with /
	url := r.URL.Path
	if d.IsDir() {
		if url[len(url)-1] != '/' {
			localRedirect(w, r, path.Base(url)+"/")
			return
		}
	} else {
		if url[len(url)-1] == '/' {
			localRedirect(w, r, "../"+path.Base(url))
			return
		}
	}
}

if d.IsDir() {
	url := r.URL.Path
	// redirect if the directory name doesn't end in a slash
	if url == "" || url[len(url)-1] != '/' {
		localRedirect(w, r, path.Base(url)+"/")
		return
	}

	// use contents of index.html for directory, if present
	index := strings.TrimSuffix(name, "/") + indexPage
	ff, err := fs.Open(index)
	if err == nil {
		defer ff.Close()
		dd, err := ff.Stat()
		if err == nil {
			d = dd
			f = ff
		}
	}
}
......

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what does it mean?

}
f.Close()

fileServer.ServeHTTP(c.Writer, c.Request)
}
}
Expand Down