Skip to content

Instantly share code, notes, and snippets.

@rfyiamcool
Last active August 20, 2020 02:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rfyiamcool/a77a80a8256c7956731ee7b7f615c48e to your computer and use it in GitHub Desktop.
Save rfyiamcool/a77a80a8256c7956731ee7b7f615c48e to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"os"
"os/user"
"runtime"
)
func userHomeDir() string {
if runtime.GOOS == "windows" {
home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
if home == "" {
home = os.Getenv("USERPROFILE")
}
return home
} else if runtime.GOOS == "linux" {
home := os.Getenv("XDG_CONFIG_HOME")
if home != "" {
return home
}
}
return os.Getenv("HOME")
}
func main() {
fmt.Println(userHomeDir())
usr, err := user.Current()
if err != nil {
panic(err)
}
fmt.Println("Name : ", usr.Name)
fmt.Println("User's home directory is : ", usr.HomeDir)
}
@rfyiamcool
Copy link
Author

shell $HOME is /root
user Name : root
User's home directory is : /root

@rfyiamcool
Copy link
Author

if u use golang write ~/file, raise panic. how to fix ? first get user home, then write userHomeDir + file.

panic: open ~/test111: no such file or directory


goroutine 1 [running]:
main.check(...)
    /root/github/a.go:12
main.main()
    /root/github/a.go:19 +0xa0
exit status 2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment