patterngoCritical
Obtain user's home directory
Viewed 0 times
userdirectoryhomeobtain
Problem
Is the following the best way of obtaining the running user's home directory? Or is there a specific function that I've ovelooked?
If the above is correct, does anyone happen to know whether this approach is guaranteed to work on non-Linux platforms, e.g. Windows?
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?
Solution
Since go 1.12 the recommended way is:
Old recommendation:
In go 1.0.3 ( probably earlier, too ) the following works:
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 )
}Code Snippets
package main
import (
"os"
"fmt"
"log"
)
func main() {
dirname, err := os.UserHomeDir()
if err != nil {
log.Fatal( err )
}
fmt.Println( dirname )
}package main
import (
"os/user"
"fmt"
"log"
)
func main() {
usr, err := user.Current()
if err != nil {
log.Fatal( err )
}
fmt.Println( usr.HomeDir )
}Context
Stack Overflow Q#7922270, score: 273
Revisions (0)
No revisions yet.