-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathexample_test.go
More file actions
96 lines (74 loc) · 1.84 KB
/
example_test.go
File metadata and controls
96 lines (74 loc) · 1.84 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package axon_test
import (
"fmt"
"github.com/eddieowens/axon"
)
// Whenever Injector.Add is called, the value is updated within the Injector only. If you've already called Get from the
// Injector before an Add is called, the value you hold is not updated, for example
func ExampleNewProvider() {
type Server struct {
ApiKey *axon.Provider[string] `inject:"api_key"`
}
axon.Add("api_key", axon.NewProvider("123"))
server := new(Server)
_ = axon.Inject(server)
fmt.Println(server.ApiKey.Get())
axon.Add("api_key", axon.NewProvider("456"))
fmt.Println(server.ApiKey.Get())
// Output:
// 123
// 456
}
func ExampleNewFactory() {
type Service struct {
DBClient DBClient `inject:",type"`
}
axon.Add(axon.NewTypeKeyFactory[DBClient](axon.NewFactory[DBClient](func(_ axon.Injector) (DBClient, error) {
// construct the DB client.
return &dbClient{}, nil
})))
s := new(Service)
_ = axon.Inject(s)
s.DBClient.DeleteUser("user")
// Output:
// Deleting user from DB!
}
// Simple example of adding values to the injector.
func ExampleAdd() {
// Use a string key
axon.Add("key", "val")
val := axon.MustGet[string](axon.WithKey("key"))
fmt.Println(val)
// Use a type as a key
axon.Add(axon.NewTypeKey(1))
i := axon.MustGet[int]()
fmt.Println(i)
// Output:
// val
// 1
}
// Simple example of injecting values into a struct
func ExampleInject() {
type ExampleStruct struct {
Val string `inject:"val"`
Int int `inject:",type"`
}
axon.Add("val", "val")
axon.Add(axon.NewTypeKey[int](1))
// Only struct pointers allowed.
out := new(ExampleStruct)
_ = axon.Inject(out)
fmt.Println(out.Val)
fmt.Println(out.Int)
// Output:
// val
// 1
}
// Simple example of getting values from the injector.
func ExampleGet() {
axon.Add("key", "val")
val := axon.MustGet[string](axon.WithKey("key"))
fmt.Println(val)
// Output:
// val
}