-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.go
58 lines (47 loc) · 1.35 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
package main
import (
"context"
"io/ioutil"
"net/http"
"cloud.google.com/go/pubsub"
"github.com/direktiv/direktiv-apps/pkg/direktivapps"
"google.golang.org/api/option"
)
type PubSubInput struct {
ServiceAccountKey string `json:"serviceAccountKey"`
Message string `json:"message"`
ProjectID string `json:"project-id"`
TopicID string `json:"topic-id"`
Attributes map[string]string `json:"attributes"`
}
const code = "com.google-pubsub.error"
func main() {
direktivapps.StartServer(GooglePubSub)
}
func GooglePubSub(w http.ResponseWriter, r *http.Request) {
obj := new(PubSubInput)
_, err := direktivapps.Unmarshal(obj, r)
if err != nil {
direktivapps.RespondWithError(w, code, err.Error())
return
}
err = ioutil.WriteFile("/key.json", []byte(obj.ServiceAccountKey), 0700)
if err != nil {
direktivapps.RespondWithError(w, code, err.Error())
return
}
ctx := context.Background()
client, err := pubsub.NewClient(ctx, obj.ProjectID, option.WithCredentialsFile("/key.json"))
if err != nil {
direktivapps.RespondWithError(w, code, err.Error())
return
}
topic := client.Topic(obj.TopicID)
topic.Publish(ctx, &pubsub.Message{
Data: []byte(obj.Message),
Attributes: obj.Attributes,
})
topic.Stop()
client.Close()
direktivapps.Respond(w, []byte{})
}