os: add examples of environment functions
For #16360.
Change-Id: Iaa3548704786018eacec530f7a907b976fa532fe
Reviewed-on: https://go-review.googlesource.com/27443
Run-TryBot: Russ Cox <rsc@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
diff --git a/src/os/example_test.go b/src/os/example_test.go
index 9c890c45..07f9c76 100644
--- a/src/os/example_test.go
+++ b/src/os/example_test.go
@@ -61,3 +61,46 @@
// Output:
// file does not exist
}
+
+func init() {
+ os.Setenv("USER", "gopher")
+ os.Setenv("HOME", "/usr/gopher")
+ os.Unsetenv("GOPATH")
+}
+
+func ExampleExpandEnv() {
+ fmt.Println(os.ExpandEnv("$USER lives in ${HOME}."))
+
+ // Output:
+ // gopher lives in /usr/gopher.
+}
+
+func ExampleLookupEnv() {
+ show := func(key string) {
+ val, ok := os.LookupEnv(key)
+ if !ok {
+ fmt.Printf("%s not set\n", key)
+ } else {
+ fmt.Printf("%s=%s\n", key, val)
+ }
+ }
+
+ show("USER")
+ show("GOPATH")
+
+ // Output:
+ // USER=gopher
+ // GOPATH not set
+}
+
+func ExampleGetenv() {
+ fmt.Printf("%s lives in %s.\n", os.Getenv("USER"), os.Getenv("HOME"))
+
+ // Output:
+ // gopher lives in /usr/gopher.
+}
+
+func ExampleUnsetenv() {
+ os.Setenv("TMPDIR", "/my/tmp")
+ defer os.Unsetenv("TMPDIR")
+}