Need to validate and clean user input of a path. When a user enters the following command line:
app.exe -f "C:\dir with space\"
The the flag value has the last quote escaped, so it's string value is:
C:\dir with space"
What do you guys recommend for a clean approach at sanitizing user input for a directory/path? Regex, or does Go have a library for dealing with this similar to filepath.Clean(), but removes trailing quote?
Edit: The cause is documented here: https://github.com/golang/go/issues/16131
For example,
package main
import (
"fmt"
"path/filepath"
"runtime"
"strings"
)
func clean(path string) string {
if runtime.GOOS == "windows" {
path = strings.TrimSuffix(path, `"`)
}
return filepath.Clean(path)
}
func main() {
path := `C:\dir with space"`
fmt.Println(path)
path = clean(path)
fmt.Println(path)
}
Output:
C:\dir with space"
C:\dir with space
Reference: MSDN: Windows: Naming Files, Paths, and Namespaces
pkgDir := flag.String( "f", "", "REQUIRED: `pkgdir` the root directory of the package")
flag.Parse()
*pkgDir = strings.TrimRight(*pkgDir, `'"`)