Obtain user's home directory
GoHome DirectoryGo Problem Overview
Is the following the best way of obtaining the running user's home directory? Or is there a specific function that I've ovelooked?
os.Getenv("HOME")
If the above is correct, does anyone happen to know whether this approach is guaranteed to work on non-Linux platforms, e.g. Windows?
Go Solutions
Solution 1 - Go
Since go 1.12 the recommended way is:
package main
import (
"os"
"fmt"
"log"
)
func main() {
dirname, err := os.UserHomeDir()
if err != nil {
log.Fatal( err )
}
fmt.Println( dirname )
}
Old recommendation:
In go 1.0.3 ( probably earlier, too ) the following works:
package main
import (
"os/user"
"fmt"
"log"
)
func main() {
usr, err := user.Current()
if err != nil {
log.Fatal( err )
}
fmt.Println( usr.HomeDir )
}
Solution 2 - Go
os.UserHomeDir()
In go1.12+ you can use os.UserHomeDir()
home, err := os.UserHomeDir()
See https://golang.org/pkg/os/#UserHomeDir
That should work even without CGO enabled (i.e. FROM scratch
) and without having to parse /etc/passwd
or other such nonsense.
Solution 3 - Go
For example,
package main
import (
"fmt"
"os"
"runtime"
)
func UserHomeDir() string {
if runtime.GOOS == "windows" {
home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
if home == "" {
home = os.Getenv("USERPROFILE")
}
return home
}
return os.Getenv("HOME")
}
func main() {
dir := UserHomeDir()
fmt.Println(dir)
}
Solution 4 - Go
Here's a nice, concise way to do it (if you're only running on a UNIX based system):
import (
"os"
)
var home string = os.Getenv("HOME")
That just queries the $HOME environment variable.
--- Edit ---
I now see that this same method was suggested above. I'll leave this example here as a distilled solution.
Solution 5 - Go
Similar answer to @peterSO but respects the XDG_CONFIG_HOME
path for linux.
package main
import (
"fmt"
"os"
"runtime"
)
func userHomeDir() string {
if runtime.GOOS == "windows" {
home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
if home == "" {
home = os.Getenv("USERPROFILE")
}
return home
} else if runtime.GOOS == "linux" {
home := os.Getenv("XDG_CONFIG_HOME")
if home != "" {
return home
}
}
return os.Getenv("HOME")
}
func main() {
fmt.Println(userHomeDir())
}
Solution 6 - Go
You should use the environment variable USERPROFILE
or HOMEPATH
under Windows. See Recognized Environment Variables (a more apropos documentation link would be welcomed).
Solution 7 - Go
go1.8rc2 has the go/build/defaultGOPATH function which gets the home directory. https://github.com/golang/go/blob/go1.8rc2/src/go/build/build.go#L260-L277
The following code is extracted from the defaultGOPATH function.
package main
import (
"fmt"
"os"
"runtime"
)
func UserHomeDir() string {
env := "HOME"
if runtime.GOOS == "windows" {
env = "USERPROFILE"
} else if runtime.GOOS == "plan9" {
env = "home"
}
return os.Getenv(env)
}
func main() {
dir := UserHomeDir()
fmt.Println(dir)
}