// file does not exist
}
-func init() {
- os.Setenv("USER", "gopher")
- os.Setenv("HOME", "/usr/gopher")
- os.Unsetenv("GOPATH")
-}
-
func ExampleExpand() {
mapper := func(placeholderName string) string {
switch placeholderName {
case "DAY_PART":
return "morning"
- case "USER":
+ case "NAME":
return "Gopher"
}
return ""
}
- fmt.Println(os.Expand("Good ${DAY_PART}, $USER!", mapper))
+ fmt.Println(os.Expand("Good ${DAY_PART}, $NAME!", mapper))
// Output:
// Good morning, Gopher!
}
func ExampleExpandEnv() {
- fmt.Println(os.ExpandEnv("$USER lives in ${HOME}."))
+ os.Setenv("NAME", "gopher")
+ os.Setenv("BURROW", "/usr/gopher")
+
+ fmt.Println(os.ExpandEnv("$NAME lives in ${BURROW}."))
// Output:
// gopher lives in /usr/gopher.
}
}
- show("USER")
- show("GOPATH")
+ os.Setenv("SOME_KEY", "value")
+ os.Setenv("EMPTY_KEY", "")
+
+ show("SOME_KEY")
+ show("EMPTY_KEY")
+ show("MISSING_KEY")
// Output:
- // USER=gopher
- // GOPATH not set
+ // SOME_KEY=value
+ // EMPTY_KEY=
+ // MISSING_KEY not set
}
func ExampleGetenv() {
- fmt.Printf("%s lives in %s.\n", os.Getenv("USER"), os.Getenv("HOME"))
+ os.Setenv("NAME", "gopher")
+ os.Setenv("BURROW", "/usr/gopher")
+
+ fmt.Printf("%s lives in %s.\n", os.Getenv("NAME"), os.Getenv("BURROW"))
// Output:
// gopher lives in /usr/gopher.
return dir, nil
}
+// UserHomeDir returns the current user's home directory.
+//
+// On Unix, including macOS, it returns the $HOME environment variable.
+// On Windows, it returns the concatenation of %HOMEDRIVE% and %HOMEPATH%.
+// On Plan 9, it returns the $home environment variable.
+func UserHomeDir() string {
+ if runtime.GOOS == "windows" {
+ return Getenv("HOMEDRIVE") + Getenv("HOMEPATH")
+ }
+ if runtime.GOOS == "plan9" {
+ return Getenv("home")
+ }
+ if runtime.GOOS == "nacl" {
+ return "/"
+ }
+ return Getenv("HOME")
+}
+
// Chmod changes the mode of the named file to mode.
// If the file is a symbolic link, it changes the mode of the link's target.
// If there is an error, it will be of type *PathError.
t.Logf("second close returned expected error %q", err)
}
}
+
+func TestUserHomeDir(t *testing.T) {
+ dir := UserHomeDir()
+ if dir == "" {
+ t.Fatal("UserHomeDir returned an empty string")
+ }
+ fi, err := Stat(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !fi.IsDir() {
+ t.Fatalf("dir %s is not directory; type = %v", dir, fi.Mode())
+ }
+}