Last active
August 20, 2020 02:58
-
-
Save rfyiamcool/a77a80a8256c7956731ee7b7f615c48e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
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
shell $HOME is /root
user Name : root
User's home directory is : /root