-
Notifications
You must be signed in to change notification settings - Fork 218
/
main.go
109 lines (93 loc) · 2.69 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
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
97
98
99
100
101
102
103
104
105
106
107
108
109
package main
import (
"context"
"fmt"
"log"
"net/url"
"os"
"time"
"github.com/cloudevents/sdk-go"
"github.com/google/uuid"
"github.com/kelseyhightower/envconfig"
)
const (
count = 1
)
type envConfig struct {
// Target URL where to send cloudevents
Target string `envconfig:"TARGET" default:"http://localhost:8080" required:"true"`
}
func main() {
var env envConfig
if err := envconfig.Process("", &env); err != nil {
log.Printf("[ERROR] Failed to process env var: %s", err)
os.Exit(1)
}
os.Exit(_main(os.Args[1:], env))
}
// Basic data struct.
type Example struct {
Sequence int `json:"id"`
Message string `json:"message"`
}
func _main(args []string, env envConfig) int {
source, err := url.Parse("https://github.com/cloudevents/sdk-go/cmd/samples/sender")
if err != nil {
log.Printf("failed to parse source url, %v", err)
return 1
}
ctx := cloudevents.ContextWithEncoding(context.Background(), cloudevents.Structured)
seq := 0
for _, contentType := range []string{"application/json", "application/xml"} {
for _, encoding := range []cloudevents.HTTPEncoding{cloudevents.HTTPBinaryV01, cloudevents.HTTPStructuredV01, cloudevents.HTTPBinaryV02, cloudevents.HTTPStructuredV02} {
t, err := cloudevents.NewHTTPTransport(
cloudevents.WithTarget(env.Target),
cloudevents.WithEncoding(encoding),
//cloudevents.WithContextBasedEncoding(), // toggle this or WithEncoding to see context based encoding work.
)
if err != nil {
log.Printf("failed to create transport, %v", err)
return 1
}
c, err := cloudevents.NewClient(t,
cloudevents.WithTimeNow(),
)
if err != nil {
log.Printf("failed to create client, %v", err)
return 1
}
message := fmt.Sprintf("Hello, %s!", encoding)
for i := 0; i < count; i++ {
event := cloudevents.Event{
Context: cloudevents.EventContextV01{
EventID: uuid.New().String(),
EventType: "com.cloudevents.sample.sent",
Source: cloudevents.URLRef{URL: *source},
ContentType: &contentType,
}.AsV01(),
Data: &Example{
Sequence: i,
Message: message,
},
}
if _, resp, err := c.Send(ctx, event); err != nil {
log.Printf("failed to send: %v", err)
} else if resp != nil {
fmt.Printf("Response:\n%s\n", resp)
fmt.Printf("Got Event Response Context: %+v\n", resp.Context)
data := &Example{}
if err := resp.DataAs(data); err != nil {
fmt.Printf("Got Data Error: %s\n", err.Error())
}
fmt.Printf("Got Response Data: %+v\n", data)
fmt.Printf("----------------------------\n")
} else {
log.Printf("event sent at %s", time.Now())
}
seq++
time.Sleep(500 * time.Millisecond)
}
}
}
return 0
}