forked from cloudevents/sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
65 lines (54 loc) · 1.57 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
/*
Copyright 2021 The CloudEvents Authors
SPDX-License-Identifier: Apache-2.0
*/
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/kelseyhightower/envconfig"
cloudevents "github.com/cloudevents/sdk-go/v2"
)
type envConfig struct {
// Port on which to listen for cloudevents
Port int `envconfig:"RCV_PORT" default:"8080"`
Path string `envconfig:"RCV_PATH" default:"/"`
}
type Example struct {
Sequence int `json:"id"`
Message string `json:"message"`
}
func gotEvent(event cloudevents.Event) error {
fmt.Printf("Got Event Context: %+v\n", event.Context)
data := &Example{}
if err := event.DataAs(data); err != nil {
fmt.Printf("Got Data Error: %s\n", err.Error())
}
fmt.Printf("Got Data: %+v\n", data)
fmt.Printf("----------------------------\n")
return nil
}
func main() {
var env envConfig
if err := envconfig.Process("", &env); err != nil {
log.Fatalf("Failed to process env var: %s", err)
}
p, err := cloudevents.NewHTTP(cloudevents.WithPort(env.Port), cloudevents.WithPath(env.Path))
if err != nil {
log.Fatalf("Failed to create protocol: %s", err.Error())
}
c, err := cloudevents.NewClient(p)
if err != nil {
log.Fatalf("Failed to create client, %v", err)
}
// Create a context that expires in 5 seconds
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
log.Printf("Starting listening on %d%s @ %s\n", env.Port, env.Path, time.Now())
if err := c.StartReceiver(ctx, gotEvent); err != nil {
log.Fatalf("Failed to start receiver: %s", err.Error())
}
log.Printf("Stopped @ %s", time.Now())
}