Obtain user's home directory

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


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.


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