git » gofer » commit 4c1de09

fileserver: Simplify path cleanup logic

author Alberto Bertogli
2022-10-06 18:51:35 UTC
committer Alberto Bertogli
2022-10-09 11:34:34 UTC
parent 622caa083d08217fca010f4538da2f5076aebdca

fileserver: Simplify path cleanup logic

This patch just simplifies the logic around path cleanup, and ensuring
that they always have an initial "/".

server/fileserver.go +5 -11

diff --git a/server/fileserver.go b/server/fileserver.go
index 0be02f5..60f943e 100644
--- a/server/fileserver.go
+++ b/server/fileserver.go
@@ -27,15 +27,6 @@ type fileServer struct {
 }
 
 func (fsrv *fileServer) ServeHTTP(w http.ResponseWriter, req *http.Request) {
-	// Ensure the URL path begins with a /.
-	{
-		upath := req.URL.Path
-		if !strings.HasPrefix(upath, "/") {
-			upath = "/" + upath
-			req.URL.Path = upath
-		}
-	}
-
 	// Redirect x/index.html to x/
 	const indexhtml = "/index.html"
 	if strings.HasSuffix(req.URL.Path, indexhtml) {
@@ -43,8 +34,11 @@ func (fsrv *fileServer) ServeHTTP(w http.ResponseWriter, req *http.Request) {
 		return
 	}
 
-	// Clean the path up. Removes the .., and it will end in a slash only if
-	// it is the root.
+	// Clean the path up. Add initial / if missing, removes the .., and it
+	// will end in a slash only if it is the root.
+	if !strings.HasPrefix(req.URL.Path, "/") {
+		req.URL.Path = "/" + req.URL.Path
+	}
 	cleanPath := path.Clean(req.URL.Path)
 
 	// Open and stat the path.