Go's Clean function to clean up file paths

2021/10/27

I wanted to draw your attention to Go’s “path.Clean()” function, which can be used to handle all the “..” aspects of file paths. You can use this to handle the case of HTTP requests with URLs that attempt to “escape” from the document root.

package main

import (
        "fmt"
        "path"
)

func main() {
        fmt.Println("/subdir1/../subdir2/index.html");
        fmt.Println(path.Clean("/subdir1/../subdir2/index.html"));
}

Results in:

% go run clean.go 
/subdir1/../subdir2/index.html
/subdir2/index.html