-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_test.go
More file actions
90 lines (74 loc) · 1.71 KB
/
Copy pathexample_test.go
File metadata and controls
90 lines (74 loc) · 1.71 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
package framework_test
import (
"context"
"fmt"
"time"
framework "github.com/roboslone/go-framework/v2"
)
// ExampleState describes example application, both configuration and runtime.
type ExampleState struct {
// configuration
Interval time.Duration
MaxIterations int
// runtime
Channel chan int
}
// Sender is a simple module, that sends increasing integers to `Channel` each `Interval`.
type Sender struct{}
func (*Sender) Start(ctx context.Context, s *ExampleState) error {
go func() {
defer close(s.Channel)
ticker := time.NewTicker(s.Interval)
var i int
for {
select {
case <-ticker.C:
s.Channel <- i
i++
if i >= s.MaxIterations {
return
}
case <-ctx.Done():
return
}
}
}()
return nil
}
// Receiver is a simple module, that prints values from `Channel`.
// It depends on Sender.
type Receiver struct{}
func (*Receiver) Start(ctx context.Context, s *ExampleState) error {
for i := range s.Channel {
fmt.Println(i)
}
return nil
}
func (*Receiver) Dependencies(_ context.Context) []string {
return []string{
"sender",
}
}
func ExampleApplication() {
// app contains all available modules and their dependencies.
app := framework.NewApplication[ExampleState](
"counter",
framework.Modules{
"sender": &Sender{},
"receiver": &Receiver{},
},
)
state := &ExampleState{
Interval: 75 * time.Millisecond,
MaxIterations: 3,
Channel: make(chan int),
}
// Ensure each module satisfies at least one module interface.
fmt.Println("check error:", app.Check())
fmt.Println("run error:", app.Run(context.Background(), context.Background(), state, "receiver"))
// Output: check error: <nil>
// 0
// 1
// 2
// run error: <nil>
}