-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_endpoints.go
295 lines (263 loc) · 7.54 KB
/
http_endpoints.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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
package local_bucketing_proxy
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
devcycle "github.com/devcyclehq/go-server-sdk/v2"
devcycle_api "github.com/devcyclehq/go-server-sdk/v2/api"
"github.com/gin-gonic/gin"
)
func Health(c *gin.Context) {
c.Status(200)
}
func Variable() gin.HandlerFunc {
return func(c *gin.Context) {
client := c.Value("devcycle").(*devcycle.Client)
user := getUserFromBody(c)
if user == nil {
return
}
if c.Param("key") == "" {
variables, err := client.AllVariables(*user)
if err != nil {
fmt.Println(err)
c.JSON(http.StatusInternalServerError, gin.H{})
return
}
c.JSON(http.StatusOK, variables)
return
}
variable, err := client.Variable(*user, c.Param("key"), nil)
if err != nil {
fmt.Println(err)
c.JSON(http.StatusInternalServerError, gin.H{})
return
}
if !variable.IsDefaulted {
c.JSON(http.StatusOK, variable.BaseVariable)
} else {
c.JSON(http.StatusNotFound, gin.H{
"message": "Variable not found for key: " + c.Param("key"),
"statusCode": http.StatusNotFound,
})
}
}
}
func Feature() gin.HandlerFunc {
return func(c *gin.Context) {
client := c.Value("devcycle").(*devcycle.Client)
user := getUserFromBody(c)
if user == nil {
return
}
allFeatures, err := client.AllFeatures(*user)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{})
return
}
c.JSON(http.StatusOK, allFeatures)
}
}
func Track() gin.HandlerFunc {
return func(c *gin.Context) {
client := c.Value("devcycle").(*devcycle.Client)
event := getEventFromBody(c)
for _, e := range event.Events {
if e.MetaData == nil {
e.MetaData = make(map[string]interface{})
}
e.MetaData["sdkProxy"] = Version
_, err := client.Track(event.User.User, e)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{})
}
}
}
}
func BatchEvents() gin.HandlerFunc {
return func(c *gin.Context) {
client := c.Value("devcycle").(*devcycle.Client)
body, err := io.ReadAll(c.Request.Body)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": "Error reading request body: " + err.Error()})
return
}
defer c.Request.Body.Close()
var batchEvents map[string]interface{}
err = json.Unmarshal(body, &batchEvents)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": "Error unmarshaling request body: " + err.Error()})
return
}
batchArray, exists := batchEvents["batch"].([]interface{})
if !exists {
c.JSON(http.StatusInternalServerError, gin.H{"message": "Missing 'batch' key in request body"})
return
}
for _, batchItem := range batchArray {
batchMap, ok := batchItem.(map[string]interface{})
if !ok {
continue
}
events, ok := batchMap["events"].([]interface{})
if !ok {
continue
}
for i, eventInterface := range events {
event, ok := eventInterface.(map[string]interface{})
if !ok {
continue
}
if _, exists := event["metaData"]; !exists {
event["metaData"] = make(map[string]interface{})
}
metadata, ok := event["metaData"].(map[string]interface{})
if !ok {
event["metaData"] = make(map[string]interface{})
metadata = event["metaData"].(map[string]interface{})
}
metadata["sdkProxy"] = Version
events[i] = event
}
batchMap["events"] = events
}
modifiedBody, err := json.Marshal(batchEvents)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": "Error marshaling modified request body: " + err.Error()})
return
}
// Passthrough proxy to the configured events api endpoint.
httpC := http.DefaultClient
req, err := http.NewRequest("POST", client.DevCycleOptions.EventsAPIURI+"/v1/events/batch", bytes.NewBuffer(modifiedBody))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": "Error creating request: " + err.Error()})
return
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", c.Request.Header.Get("Authorization"))
resp, err := httpC.Do(req)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": "Error sending request: " + err.Error()})
return
}
respBody, err := io.ReadAll(resp.Body)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": "Error reading response: " + err.Error()})
return
}
defer resp.Body.Close()
c.Data(resp.StatusCode, resp.Header.Get("Content-Type"), respBody)
}
}
func GetConfig(client *devcycle.Client, version ...string) gin.HandlerFunc {
return func(c *gin.Context) {
instance := c.Value("instance").(*ProxyInstance)
if c.Param("sdkKey") == "" || !strings.HasSuffix(c.Param("sdkKey"), ".json") {
c.AbortWithStatus(http.StatusForbidden)
return
}
var ret, rawConfig []byte
var etag, lm string
var err error
if client != nil {
rawConfig, etag, lm, err = client.GetRawConfig()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{})
return
}
if instance.SSEEnabled {
config := map[string]interface{}{}
err = json.Unmarshal(rawConfig, &config)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{})
return
}
hostname := fmt.Sprintf("http://%s:%d", instance.SSEHostname, instance.HTTPPort)
// This is the only indicator that a unix socket request was made
if c.Request.RemoteAddr == "" {
hostname = fmt.Sprintf("unix:%s", instance.UnixSocketPath)
}
if val, ok := config["sse"]; ok {
path := val.(map[string]interface{})["path"].(string)
config["sse"] = devcycle_api.SSEHost{
Hostname: hostname,
Path: path,
}
}
ret, err = json.Marshal(config)
} else {
ret = rawConfig
}
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{})
return
}
} else if client == nil && len(version) > 0 {
ret, etag, lm = instance.BypassSDKConfig(version[0])
}
c.Header("ETag", etag)
c.Header("Last-Modified", lm)
c.Data(http.StatusOK, "application/json", ret)
}
}
func SSE() gin.HandlerFunc {
return func(c *gin.Context) {
instance := c.Value("instance").(*ProxyInstance)
instance.sseServer.Handler(instance.SDKKey).ServeHTTP(c.Writer, c.Request)
}
}
func getUserFromBody(c *gin.Context) *devcycle.User {
if c.Param("key") != strings.ToLower(c.Param("key")) {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
"message": "Variable Key must be lowercase",
"statusCode": http.StatusBadRequest,
})
return nil
}
var user devcycle.User
jsonBody, err := io.ReadAll(c.Request.Body)
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
"message": "Missing JSON body",
"exception": err.Error(),
"statusCode": http.StatusBadRequest,
})
return nil
}
defer c.Request.Body.Close()
err = json.Unmarshal(jsonBody, &user)
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
"message": "Invalid JSON body",
"exception": err.Error(),
"statusCode": http.StatusBadRequest,
})
return nil
}
return &user
}
func getEventFromBody(c *gin.Context) *devcycle.UserDataAndEventsBody {
var event devcycle.UserDataAndEventsBody
jsonBody, err := io.ReadAll(c.Request.Body)
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
"message": "Missing JSON body",
"statusCode": http.StatusBadRequest,
})
return nil
}
defer c.Request.Body.Close()
err = json.Unmarshal(jsonBody, &event)
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
"message": "Invalid JSON body",
"exception": err.Error(),
"statusCode": http.StatusBadRequest,
})
return nil
}
return &event
}