-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
86 lines (72 loc) · 1.66 KB
/
Copy pathmain.go
File metadata and controls
86 lines (72 loc) · 1.66 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
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"os"
"github.com/exanubes/appsync"
"github.com/exanubes/appsync/authorizer"
)
func events(e ...[]byte) [][]byte { return e }
func requiredEnv(name string) string {
value := os.Getenv(name)
if value == "" {
log.Fatalf("%s is required", name)
}
return value
}
func main() {
var (
httpEndpoint = requiredEnv("APPSYNC_HTTP_ENDPOINT")
wsEndpoint = requiredEnv("APPSYNC_WS_ENDPOINT")
apiKey = requiredEnv("APPSYNC_API_KEY")
channel = requiredEnv("APPSYNC_CHANNEL")
)
ctx := context.Background()
authz, err := authorizer.ApiKey(authorizer.ApiKeyAuthorizerConfig{
ApiKey: apiKey,
Endpoint: httpEndpoint,
})
if err != nil {
log.Fatal(err)
}
client, err := appsync.Connect(ctx, appsync.ConnectionOptions{
Endpoint: wsEndpoint,
Subprotocols: []string{appsync.ProtocolEvents},
Authorizers: appsync.Authorizers{Default: authz},
})
if err != nil {
log.Fatal(err)
}
defer client.Close(ctx)
sub, err := client.Subscribe(ctx, appsync.SubscribeCommandInput{
Channel: channel,
})
if err != nil {
log.Fatal(err)
}
defer sub.Close(ctx)
type event struct {
Message string `json:"message"`
}
payload, err := json.Marshal(event{Message: "hello from api-key example"})
if err != nil {
log.Fatal(err)
}
if _, err = client.Publish(ctx, appsync.PublishCommandInput{
Channel: channel,
Events: events(payload),
}); err != nil {
log.Fatal(err)
}
var received event
if err = sub.DecodeNext(ctx, &received); err != nil {
if errors.Is(err, appsync.ErrSubscriptionClosed) {
return
}
log.Fatal(err)
}
fmt.Println("received:", received.Message)
}