-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmain.go
111 lines (92 loc) · 2.17 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
110
111
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/render"
"github.com/sakajunquality/cloud-pubsub-events/gcrevent"
"github.com/ubie-oss/flow/v4/flow"
"gopkg.in/yaml.v3"
)
// Response is a HTTP response
type Response struct {
Status int `json:"status"`
}
// PubSubMessage is a Push message from Cloud Pub/Sub
type PubSubMessage struct {
Message struct {
Data []byte `json:"data,omitempty"`
ID string `json:"id"`
} `json:"message"`
Subscription string `json:"subscription"`
}
var (
f *flow.Flow
)
func main() {
cfg, err := getConfig()
if err != nil {
fmt.Fprintf(os.Stderr, "Cloud not read the file:%s.\n", err)
os.Exit(1)
}
f, err = initFlow(cfg)
if err != nil {
fmt.Fprintf(os.Stderr, "Error parsing the config %s.\n", err)
os.Exit(1)
}
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(middleware.Logger)
r.Post("/", handlePubSubMessage)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
log.Fatal(http.ListenAndServe(":"+port, r))
}
func getConfig() ([]byte, error) {
return os.ReadFile(os.Getenv("FLOW_CONFIG_PATH"))
}
func initFlow(config []byte) (*flow.Flow, error) {
cfg := new(flow.Config)
if err := yaml.Unmarshal(config, cfg); err != nil {
fmt.Fprintf(os.Stderr, "yaml.Unmarshal error:%v.\n", err)
os.Exit(1)
}
return flow.New(cfg)
}
func handlePubSubMessage(w http.ResponseWriter, r *http.Request) {
ctx := context.TODO()
var m PubSubMessage
body, err := io.ReadAll(r.Body)
if err != nil {
log.Printf("iotuil.ReadAll: %v", err)
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
if err := json.Unmarshal(body, &m); err != nil {
log.Printf("json.Unmarshal: %v", err)
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
event, err := gcrevent.ParseMessage(m.Message.Data)
if err != nil {
log.Printf("gcrevent.ParseMessage: %v", err)
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
err = f.ProcessGCREvent(ctx, event)
if err != nil {
log.Printf("faild to process: %s", err)
}
res := &Response{
Status: http.StatusOK,
}
render.JSON(w, r, res)
}