Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Last active March 31, 2024 19:42
Show Gist options
  • Save miguelmota/1fb071b6c8920d1a6ed27c957b1a489a to your computer and use it in GitHub Desktop.
Save miguelmota/1fb071b6c8920d1a6ed27c957b1a489a to your computer and use it in GitHub Desktop.
Golang expand user home path
// UserHomeDir ...
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")
}
// NormalizePath ...
func NormalizePath(path string) string {
// expand tilde
if strings.HasPrefix(path, "~/") {
path = filepath.Join(UserHomeDir(), path[2:])
}
return path
}
@tomruk
Copy link

tomruk commented Mar 31, 2024

XDG_CONFIG_HOME is for $HOME/.config, not $HOME.

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