Skip to content

Commit

Permalink
Merge pull request #764 from devlights/add-os-unserenv-example
Browse files Browse the repository at this point in the history
  • Loading branch information
devlights authored Feb 28, 2024
2 parents f3a6dd8 + cd739be commit 60b9169
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
1 change: 1 addition & 0 deletions examples/basic/osop/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@
| expandenv.go | osop_expandenv | os.ExpandEnv() のサンプルです。 |
| expand.go | osop_expand | os.Expand() のサンプルです。 |
| setenv.go | osop_setenv | os.Setenv() のサンプルです。 |
| unsetenv.go | osop_unsetenv | os.Unsetenv() のサンプルです。 |
1 change: 1 addition & 0 deletions examples/basic/osop/examples.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,5 @@ func (r *register) Regist(m mapping.ExampleMapping) {
m["osop_expandenv"] = ExpandEnv
m["osop_expand"] = Expand
m["osop_setenv"] = Setenv
m["osop_unsetenv"] = Unsetenv
}
66 changes: 66 additions & 0 deletions examples/basic/osop/unsetenv.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package osop

import (
"os"

"github.com/devlights/gomy/output"
)

// Unsetenv は、os.Unsetenv() のサンプルです。
//
// 指定された環境変数の値をクリアします。
// 一時的な環境変数を用意する際に、os.Setenv()とペアで以下のように
// よく利用される。
//
// os.Setenv("MYENV", "HELLOWORLD")
// defer os.Unsetenv("MYENV")
//
// # REFERENCES
//
// - https://pkg.go.dev/[email protected]#Unsetenv
func Unsetenv() error {
const (
ENVKEY = "MYENV"
ENVVAL = "HELLOWORLD"
)

var (
env string
ok bool
err error
)

err = os.Setenv(ENVKEY, ENVVAL)
if err != nil {
return err
}

env, ok = os.LookupEnv(ENVKEY)
output.Stdoutf("[MYENV(before)]", "VALUE=%q\tOK=%v\n", env, ok)

err = os.Unsetenv(ENVKEY)
if err != nil {
return err
}

env, ok = os.LookupEnv(ENVKEY)
output.Stdoutf("[MYENV(after )]", "VALUE=%q\tOK=%v\n", env, ok)

return nil

/*
$ task
task: [build] go build .
task: [run] ./try-golang -onetime
ENTER EXAMPLE NAME: osop_unsetenv
[Name] "osop_unsetenv"
[MYENV(before)] VALUE="HELLOWORLD" OK=true
[MYENV(after )] VALUE="" OK=false
[Elapsed] 70.13µs
*/

}

0 comments on commit 60b9169

Please sign in to comment.