-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
52 lines (46 loc) · 1.02 KB
/
main.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
package main
import (
"encoding/json"
"go.uber.org/dig"
"log"
"os"
)
type Config struct {
Prefix string
}
func main() {
c := dig.New()
err := c.Provide(func() (*Config, error) {
// In a real program, the configuration will probably be read from a
// file.
var cfg Config
err := json.Unmarshal([]byte(`{"prefix": "[foo] "}`), &cfg)
return &cfg, err
})
if err != nil {
panic(err)
}
// Provide a way to build the logger based on the configuration.
err = c.Provide(func(cfg *Config) *log.Logger {
return log.New(os.Stdout, cfg.Prefix, 0)
})
if err != nil {
panic(err)
}
// The second call with same paramers will cause a panic.
// Use name parameter to fix it
err = c.Provide(func(cfg *Config) *log.Logger {
return log.New(os.Stdout, cfg.Prefix, 0)
}, dig.Name("logger2"))
if err != nil {
panic(err)
}
// Invoke a function that requires the logger, which in turn builds the
// Config first.
err = c.Invoke(func(l *log.Logger) {
l.Print("You've been invoked")
})
if err != nil {
panic(err)
}
}