-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
145 lines (117 loc) · 3.32 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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package main
import (
"encoding/json"
"fmt"
"net/http"
"io"
"log"
"os"
"github.com/gorilla/mux"
"gopkg.in/segmentio/analytics-go.v3"
)
type HasuraEvent struct {
ID string `json:"id"`
Event `json:"event"`
Table `json:"table"`
Trigger `json:"trigger"`
}
type Event struct {
Op string `json:"op"`
Data `json:"data"`
}
type Data struct {
Old map[string]interface{} `json:"old"`
New map[string]interface{} `json:"new"`
}
type Table struct {
Name string `json:"name"`
Schema string `json:"schema"`
}
type Trigger struct {
ID string `json:"id"`
Name string `json:"name"`
}
type TriggerResponse struct {
Message string `json:"message"`
OldData map[string]interface{} `json:"oldData"`
NewData map[string]interface{} `json:"newData"`
}
func FetchServerHealth(w http.ResponseWriter, r *http.Request) {
// A very simple health check.
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
// In the future we could report back on the status of our DB, or our cache
// (e.g. Redis) by performing a simple PING, and include them in the response.
io.WriteString(w, `{"alive": true}`)
}
func WebhookHandler(w http.ResponseWriter, r *http.Request) {
segmentWriteKey, segmentWriteKeyExists := os.LookupEnv("SEGMENT_WRITE_API_KEY")
userIdKey, userIdKeyExists := os.LookupEnv("USER_ID_FIELD")
if !segmentWriteKeyExists {
log.Println("Poorly Configured Server - Missing Segment Write Key")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
if !userIdKeyExists {
userIdKey = "user_id"
}
decoder := json.NewDecoder(r.Body)
var event HasuraEvent
err := decoder.Decode(&event)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
response := TriggerResponse{
Message: fmt.Sprintf(
"got '%s' for '%s' operation on '%s' table in '%s' schema from '%s' trigger",
event.ID,
event.Event.Op,
event.Table.Name,
event.Table.Schema,
event.Trigger.Name,
),
OldData: event.Data.Old,
NewData: event.Data.New,
}
client, _ := analytics.NewWithConfig(segmentWriteKey, analytics.Config{
Verbose: true,
Logger: analytics.StdLogger(log.New(os.Stderr, "segment ", log.LstdFlags)),
})
user_id, ok := event.Data.New[userIdKey]
if !ok || user_id == nil {
user_id = "anonymous"
}
event_name := fmt.Sprintf("%s_%s", event.Event.Op, event.Table.Name)
event_properties := analytics.NewProperties().
Set("event_id", event.ID)
for key, value := range event.Data.New {
event_properties.Set(key, value)
}
client.Enqueue(analytics.Track{
Event: event_name,
UserId: user_id.(string),
Properties: event_properties,
})
err = json.NewEncoder(w).Encode(response)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println(r.RequestURI)
next.ServeHTTP(w, r)
})
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/webhook", WebhookHandler).Methods("POST")
r.HandleFunc("/health", FetchServerHealth).Methods("GET")
r.Use(loggingMiddleware)
log.Println("Starting Hasura Segment Source Server. Listening on port 4004 ...")
err := http.ListenAndServe(":4004", r)
if err != nil {
log.Println(err)
}
}