Get user home directory

Is the best way to get a working user home directory? Or is there a specific function that I learned?

os.Getenv("HOME") 

If the above is true, can anyone find out if this approach is guaranteed to work on platforms other than Linux? Windows?

+55
go
Oct 27 2018-11-11T00:
source share
5 answers

In go 1.0.3 (perhaps 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 cross compiling is important, consider the homedir library

+113
Oct 22 '12 at 3:50
source share

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) } 
+9
Oct 27 '11 at 22:01
source share

You must use the USERPROFILE or HOMEPATH environment variable under Windows. See Recognized environment variables (more reference to documentation).

+2
Oct. 27 2018-11-11T00:
source share

Here's a nice, concise way to do this (if you only work on a UNIX-based system):

 import ( "os" ) var home string = os.Getenv("HOME") 

It just queries the $ HOME environment variable.

--- Edit ---

Now I see that the same method was proposed above. I will leave this example here as a distilled solution.

+2
Oct 03 '13 at 18:27
source share

go1.8rc2 has a function go / build / defaultGOPATH, 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 GOPATH function by default.

 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) } 
+1
Jan 22 '17 at 1:34 on
source share



All Articles