/
example_test.go
70 lines (56 loc) · 1.22 KB
/
example_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package env_test
import (
"context"
"fmt"
"net/http"
"os"
"strconv"
"time"
envx "go.strv.io/env"
)
type debug bool
func (d *debug) UnmarshalText(text []byte) error {
if d == nil {
return fmt.Errorf("debug: UnmarshalText: nil pointer")
}
b, err := strconv.ParseBool(string(text))
if err != nil {
return err
}
*d = debug(b)
return nil
}
type serviceConfig struct {
Addr string `env:"ADDR"`
Debug *debug `env:"DEBUG"`
Metrics metricsConfig `env:",dive"`
}
type metricsConfig struct {
Namespace string `env:"METRICS_NAMESPACE"`
}
func ExampleApply() {
cfg := serviceConfig{}
err := os.Setenv("APP_PREFIX", "EXAMPLE")
if err != nil {
panic(err)
}
err = os.Setenv("EXAMPLE_ADDR", ":8080")
if err != nil {
panic(err)
}
envx.MustApply(&cfg)
//nolint:gosec
server := &http.Server{Addr: cfg.Addr}
_, _ = fmt.Println("Starting HTTP server on address: ", cfg.Addr)
go func() {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
panic(err)
}
}()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
panic(err)
}
// Output: Starting HTTP server on address: :8080
}