How do I create crossplatform file paths in Go?
Based on the answer of @EvanShaw and this blog the following code was created:
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
p := filepath.FromSlash("path/to/file")
fmt.Println("Path: " + p)
}
returns:
Path: path\to\file
on Windows.
Use path/filepath
instead of path
. path
is intended for forward slash-separated paths only (such as those used in URLs), while path/filepath
manipulates paths across different operating systems.
Example:
package main
import (
"fmt"
"path/filepath"
)
func main() {
path := filepath.Join("home", "hello", "world.txt")
fmt.Println(path)
}
Go Playground: https://go.dev/play/p/2Fpb_vJzvSb
For creating and manipulating OS-specific paths directly use os.PathSeparator
and the path/filepath
package.
An alternative method is to always use '/'
and the path
package throughout your program. The path
package uses '/'
as path separator irrespective of the OS. Before opening or creating a file, convert the /-separated path into an OS-specific path string by calling filepath.FromSlash(path string)
. Paths returned by the OS can be converted to /-separated paths by calling filepath.ToSlash(path string)
.