Obtain user's home directory

Paul Ruane picture Paul Ruane · Oct 27, 2011 · Viewed 50.3k times · Source

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?

Answer

Vlad Didenko picture Vlad Didenko · Oct 22, 2012

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 )
}

If it is important to cross-compile, consider the homedir library