-
Notifications
You must be signed in to change notification settings - Fork 732
/
dapr.go
83 lines (69 loc) 路 1.91 KB
/
dapr.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
package dapr
import (
"context"
"encoding/json"
"fmt"
daprClient "github.com/dapr/go-sdk/client"
"github.com/open-policy-agent/gatekeeper/v3/pkg/pubsub/connection"
)
type ClientConfig struct {
// Name of the component to be used for pub sub messaging
Component string `json:"component"`
}
// Dapr represents driver for interacting with pub sub using dapr.
type Dapr struct {
// Array of clients to talk to different endpoints
client daprClient.Client
// Name of the pubsub component
pubSubComponent string
}
const (
Name = "dapr"
)
func (r *Dapr) Publish(_ context.Context, data interface{}, topic string) error {
jsonData, err := json.Marshal(data)
if err != nil {
return fmt.Errorf("error marshaling data: %w", err)
}
err = r.client.PublishEvent(context.Background(), r.pubSubComponent, topic, jsonData)
if err != nil {
return fmt.Errorf("error publishing message to dapr: %w", err)
}
return nil
}
func (r *Dapr) CloseConnection() error {
return nil
}
func (r *Dapr) UpdateConnection(_ context.Context, config interface{}) error {
var cfg ClientConfig
m, ok := config.(map[string]interface{})
if !ok {
return fmt.Errorf("invalid type assertion, config is not in expected format")
}
cfg.Component, ok = m["component"].(string)
if !ok {
return fmt.Errorf("failed to get value of component")
}
r.pubSubComponent = cfg.Component
return nil
}
// Returns a new client for dapr.
func NewConnection(_ context.Context, config interface{}) (connection.Connection, error) {
var cfg ClientConfig
m, ok := config.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("invalid type assertion, config is not in expected format")
}
cfg.Component, ok = m["component"].(string)
if !ok {
return nil, fmt.Errorf("failed to get value of component")
}
tmp, err := daprClient.NewClient()
if err != nil {
return nil, err
}
return &Dapr{
client: tmp,
pubSubComponent: cfg.Component,
}, nil
}