Obtain user's home directory
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 )
}
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)
}