Last active
March 31, 2024 19:42
-
-
Save miguelmota/1fb071b6c8920d1a6ed27c957b1a489a to your computer and use it in GitHub Desktop.
Golang expand user home path
This file contains 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
// 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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
XDG_CONFIG_HOME
is for$HOME/.config
, not$HOME
.