Skip to content

Commit fb84246

Browse files
committedAug 7, 2024··
docs: more examples
1 parent be1c262 commit fb84246

File tree

1 file changed

+53
-2
lines changed

1 file changed

+53
-2
lines changed
 

‎example_test.go

+53-2
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,25 @@ import (
77
"reflect"
88
)
99

10+
// Basic package usage example.
11+
func Example() {
12+
type Config struct {
13+
Foo string `env:"FOO"`
14+
}
15+
16+
os.Setenv("FOO", "bar")
17+
18+
// parse:
19+
var cfg1 Config
20+
_ = Parse(&cfg1)
21+
22+
// parse with generics:
23+
cfg2, _ := ParseAs[Config]()
24+
25+
fmt.Print(cfg1.Foo, cfg2.Foo)
26+
// Output: barbar
27+
}
28+
1029
// Parse the environment into a struct.
1130
func ExampleParse() {
1231
type Config struct {
@@ -124,8 +143,8 @@ func ExampleParse_init() {
124143
// during `Parse`.
125144
func ExampleParse_setDefaults() {
126145
type Config struct {
127-
Foo string `env:"FOO"`
128-
Bar string `env:"BAR" envDefault:"bar"`
146+
Foo string `env:"DEF_FOO"`
147+
Bar string `env:"DEF_BAR" envDefault:"bar"`
129148
}
130149
cfg := Config{
131150
Foo: "foo",
@@ -358,3 +377,35 @@ func ExampleParse_fromFile() {
358377
fmt.Printf("%+v", cfg)
359378
// Output: {Secret:super secret}
360379
}
380+
381+
// TODO: envSeperator
382+
//
383+
384+
func ExampleParse_errorHandling() {
385+
type Config struct {
386+
Username string `env:"USERNAME" envDefault:"admin"`
387+
Password string `env:"PASSWORD,notEmpty"`
388+
}
389+
390+
var cfg Config
391+
err := Parse(&cfg)
392+
if e, ok := err.(*AggregateError); ok {
393+
for _, er := range e.Errors {
394+
switch v := er.(type) {
395+
case ParseError:
396+
// handle it
397+
case NotStructPtrError:
398+
// handle it
399+
case NoParserError:
400+
// handle it
401+
case NoSupportedTagOptionError:
402+
// handle it
403+
default:
404+
fmt.Printf("Unknown error type %v", v)
405+
}
406+
}
407+
}
408+
409+
fmt.Printf("%+v", cfg)
410+
// Output: {Username:admin Password:}
411+
}

0 commit comments

Comments
 (0)
Please sign in to comment.