Skip to content

Commit 60b9169

Browse files
authored
Merge pull request #764 from devlights/add-os-unserenv-example
2 parents f3a6dd8 + cd739be commit 60b9169

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-0
lines changed

examples/basic/osop/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,4 @@
1212
| expandenv.go | osop_expandenv | os.ExpandEnv() のサンプルです。 |
1313
| expand.go | osop_expand | os.Expand() のサンプルです。 |
1414
| setenv.go | osop_setenv | os.Setenv() のサンプルです。 |
15+
| unsetenv.go | osop_unsetenv | os.Unsetenv() のサンプルです。 |

examples/basic/osop/examples.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,5 @@ func (r *register) Regist(m mapping.ExampleMapping) {
2121
m["osop_expandenv"] = ExpandEnv
2222
m["osop_expand"] = Expand
2323
m["osop_setenv"] = Setenv
24+
m["osop_unsetenv"] = Unsetenv
2425
}

examples/basic/osop/unsetenv.go

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package osop
2+
3+
import (
4+
"os"
5+
6+
"github.com/devlights/gomy/output"
7+
)
8+
9+
// Unsetenv は、os.Unsetenv() のサンプルです。
10+
//
11+
// 指定された環境変数の値をクリアします。
12+
// 一時的な環境変数を用意する際に、os.Setenv()とペアで以下のように
13+
// よく利用される。
14+
//
15+
// os.Setenv("MYENV", "HELLOWORLD")
16+
// defer os.Unsetenv("MYENV")
17+
//
18+
// # REFERENCES
19+
//
20+
// - https://pkg.go.dev/os@go1.22.0#Unsetenv
21+
func Unsetenv() error {
22+
const (
23+
ENVKEY = "MYENV"
24+
ENVVAL = "HELLOWORLD"
25+
)
26+
27+
var (
28+
env string
29+
ok bool
30+
err error
31+
)
32+
33+
err = os.Setenv(ENVKEY, ENVVAL)
34+
if err != nil {
35+
return err
36+
}
37+
38+
env, ok = os.LookupEnv(ENVKEY)
39+
output.Stdoutf("[MYENV(before)]", "VALUE=%q\tOK=%v\n", env, ok)
40+
41+
err = os.Unsetenv(ENVKEY)
42+
if err != nil {
43+
return err
44+
}
45+
46+
env, ok = os.LookupEnv(ENVKEY)
47+
output.Stdoutf("[MYENV(after )]", "VALUE=%q\tOK=%v\n", env, ok)
48+
49+
return nil
50+
51+
/*
52+
$ task
53+
task: [build] go build .
54+
task: [run] ./try-golang -onetime
55+
56+
ENTER EXAMPLE NAME: osop_unsetenv
57+
58+
[Name] "osop_unsetenv"
59+
[MYENV(before)] VALUE="HELLOWORLD" OK=true
60+
[MYENV(after )] VALUE="" OK=false
61+
62+
63+
[Elapsed] 70.13µs
64+
*/
65+
66+
}

0 commit comments

Comments
 (0)