-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathserver_test.go
598 lines (559 loc) · 19 KB
/
server_test.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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
// Copyright 2020 The Cloud Native Events Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package restapi_test
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"sync"
"testing"
"time"
cloudevents "github.com/cloudevents/sdk-go/v2"
types2 "github.com/cloudevents/sdk-go/v2/types"
"github.com/google/uuid"
restapi "github.com/redhat-cne/rest-api"
"github.com/redhat-cne/sdk-go/pkg/channel"
"github.com/redhat-cne/sdk-go/pkg/event"
"github.com/redhat-cne/sdk-go/pkg/event/ptp"
"github.com/redhat-cne/sdk-go/pkg/pubsub"
"github.com/redhat-cne/sdk-go/pkg/types"
v1event "github.com/redhat-cne/sdk-go/v1/event"
api "github.com/redhat-cne/sdk-go/v1/pubsub"
log "github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"golang.org/x/net/context"
)
var (
server *restapi.Server
eventOutCh chan *channel.DataChan
closeCh chan struct{}
wg sync.WaitGroup
port = 8989
apPath = "/routes/cne/v1/"
resource = "test/test"
resourceNoneSubscribed = "test/nonesubscribed"
storePath = "."
ObjSub pubsub.PubSub
ObjPub pubsub.PubSub
)
func init() {
eventOutCh = make(chan *channel.DataChan, 10)
closeCh = make(chan struct{})
}
func TestMain(m *testing.M) {
server = restapi.InitServer(port, apPath, storePath, eventOutCh, closeCh)
//start http server
server.Start()
wg.Add(1)
go func() {
for d := range eventOutCh {
if d.Type == channel.STATUS && d.StatusChan != nil {
clientID, _ := uuid.Parse("123e4567-e89b-12d3-a456-426614174001")
cneEvent := v1event.CloudNativeEvent()
cneEvent.SetID(ObjPub.ID)
cneEvent.Type = string(ptp.PtpStateChange)
cneEvent.SetTime(types.Timestamp{Time: time.Now().UTC()}.Time)
cneEvent.SetDataContentType(event.ApplicationJSON)
data := event.Data{
Version: "event",
Values: []event.DataValue{{
Resource: "test",
DataType: event.NOTIFICATION,
ValueType: event.ENUMERATION,
Value: ptp.ACQUIRING_SYNC,
},
},
}
data.SetVersion("v1") //nolint:errcheck
cneEvent.SetData(data)
e := cloudevents.Event{
Context: cloudevents.EventContextV1{
Type: string(ptp.PtpStateChange),
Source: cloudevents.URIRef{URL: url.URL{Scheme: "http", Host: "example.com", Path: "/source"}},
ID: "status event",
Time: &cloudevents.Timestamp{Time: time.Date(2020, 03, 21, 12, 34, 56, 780000000, time.UTC)},
DataSchema: &types2.URI{URL: url.URL{Scheme: "http", Host: "example.com", Path: "/schema"}},
Subject: func(s string) *string { return &s }("topic"),
}.AsV1(),
}
_ = e.SetData("", cneEvent)
func() {
defer func() {
if err := recover(); err != nil {
log.Errorf("error on close channel")
}
}()
if d.Address == resourceNoneSubscribed {
d.StatusChan <- &channel.StatusChan{
ID: "123",
ClientID: clientID,
Data: &e,
StatusCode: http.StatusBadRequest,
Message: []byte("Client not subscribed"),
}
} else {
d.StatusChan <- &channel.StatusChan{
ID: "123",
ClientID: clientID,
Data: &e,
StatusCode: http.StatusOK,
Message: []byte("ok"),
}
}
}()
}
log.Infof("incoming data %#v", d)
}
}()
time.Sleep(2 * time.Second)
port = server.Port()
exitVal := m.Run()
os.Exit(exitVal)
}
func TestServer_Health(t *testing.T) {
// CHECK URL IS UP
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", fmt.Sprintf("http://localhost:%d%s%s", port, apPath, "health"), nil)
assert.Nil(t, err)
req.Header.Set("Content-Type", "application/json")
resp, err := server.HTTPClient.Do(req)
assert.Nil(t, err)
defer resp.Body.Close()
assert.Equal(t, http.StatusOK, resp.StatusCode)
}
func TestServer_CreateSubscription(t *testing.T) {
// create subscription
sub := api.NewPubSub(
&types.URI{URL: url.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port), Path: fmt.Sprintf("%s%s", apPath, "dummy")}},
resource, "1.0")
data, err := json.Marshal(&sub)
assert.Nil(t, err)
assert.NotNil(t, data)
/// create new subscription
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "POST", fmt.Sprintf("http://localhost:%d%s%s", port, apPath, "subscriptions"), bytes.NewBuffer(data))
assert.Nil(t, err)
req.Header.Set("Content-Type", "application/json")
resp, err := server.HTTPClient.Do(req)
assert.Nil(t, err)
defer resp.Body.Close()
bodyBytes, err := io.ReadAll(resp.Body)
assert.Nil(t, err)
bodyString := string(bodyBytes)
log.Print(bodyString)
assert.Equal(t, http.StatusCreated, resp.StatusCode)
err = json.Unmarshal(bodyBytes, &ObjSub)
assert.Nil(t, err)
assert.NotEmpty(t, ObjSub.ID)
assert.NotEmpty(t, ObjSub.URILocation)
assert.NotEmpty(t, ObjSub.EndPointURI)
assert.NotEmpty(t, ObjSub.Resource)
assert.Equal(t, sub.Resource, ObjSub.Resource)
log.Infof("Subscription:\n%s", ObjSub.String())
}
func TestServer_GetSubscription(t *testing.T) {
// Get Just Created Subscription
req, err := http.NewRequest("GET", fmt.Sprintf("http://localhost:%d%s%s/%s", port, apPath, "subscriptions", ObjSub.ID), nil)
assert.Nil(t, err)
req.Header.Set("Content-Type", "application/json")
resp, err := server.HTTPClient.Do(req)
assert.Nil(t, err)
defer resp.Body.Close()
bodyBytes, err := io.ReadAll(resp.Body)
assert.Nil(t, err)
rSub := api.New()
err = json.Unmarshal(bodyBytes, &rSub)
if e, ok := err.(*json.SyntaxError); ok {
log.Infof("syntax error at byte offset %d", e.Offset)
}
assert.Nil(t, err)
assert.Equal(t, rSub.ID, ObjSub.ID)
}
func TestServer_CreatePublisher(t *testing.T) {
pub := pubsub.PubSub{
ID: "",
EndPointURI: &types.URI{URL: url.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port), Path: fmt.Sprintf("%s%s", apPath, "dummy")}},
Resource: resource,
}
pubData, err := json.Marshal(&pub)
assert.Nil(t, err)
assert.NotNil(t, pubData)
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "POST", fmt.Sprintf("http://localhost:%d%s%s", port, apPath, "publishers"), bytes.NewBuffer(pubData))
assert.Nil(t, err)
req.Header.Set("Content-Type", "application/json")
resp, err := server.HTTPClient.Do(req)
assert.Nil(t, err)
defer resp.Body.Close()
pubBodyBytes, err := io.ReadAll(resp.Body)
assert.Nil(t, err)
err = json.Unmarshal(pubBodyBytes, &ObjPub)
assert.Nil(t, err)
assert.Equal(t, http.StatusCreated, resp.StatusCode)
assert.NotEmpty(t, ObjPub.ID)
assert.NotEmpty(t, ObjPub.URILocation)
assert.NotEmpty(t, ObjPub.EndPointURI)
assert.NotEmpty(t, ObjPub.Resource)
assert.Equal(t, pub.Resource, ObjPub.Resource)
log.Infof("publisher \n%s", ObjPub.String())
}
func TestServer_GetPublisher(t *testing.T) {
// Get Just created Publisher
req, err := http.NewRequest("GET", fmt.Sprintf("http://localhost:%d%s%s/%s", port, apPath, "publishers", ObjPub.ID), nil)
assert.Nil(t, err)
req.Header.Set("Content-Type", "application/json")
resp, err := server.HTTPClient.Do(req)
assert.Nil(t, err)
defer resp.Body.Close()
pubBodyBytes, err := io.ReadAll(resp.Body)
assert.Nil(t, err)
var rPub pubsub.PubSub
log.Printf("the data %s", string(pubBodyBytes))
err = json.Unmarshal(pubBodyBytes, &rPub)
assert.Equal(t, resp.StatusCode, http.StatusOK)
assert.Nil(t, err)
assert.Equal(t, ObjPub.ID, rPub.ID)
}
func TestServer_ListSubscriptions(t *testing.T) {
// Get All Subscriptions
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", fmt.Sprintf("http://localhost:%d%s%s", port, apPath, "subscriptions"), nil)
assert.Nil(t, err)
req.Header.Set("Content-Type", "application/json")
resp, err := server.HTTPClient.Do(req)
assert.Nil(t, err)
defer resp.Body.Close() // Close body only if response non-nil
bodyBytes, err := io.ReadAll(resp.Body)
assert.Nil(t, err)
var subList []pubsub.PubSub
log.Printf("TestServer_ListSubscriptions :%s\n", string(bodyBytes))
err = json.Unmarshal(bodyBytes, &subList)
assert.Nil(t, err)
assert.Greater(t, len(subList), 0)
}
func TestServer_ListPublishers(t *testing.T) {
// Get All Publisher
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", fmt.Sprintf("http://localhost:%d%s%s", port, apPath, "publishers"), nil)
assert.Nil(t, err)
req.Header.Set("Content-Type", "application/json")
resp, err := server.HTTPClient.Do(req)
assert.Nil(t, err)
defer resp.Body.Close()
pubBodyBytes, err := io.ReadAll(resp.Body)
assert.Nil(t, err)
var pubList []pubsub.PubSub
err = json.Unmarshal(pubBodyBytes, &pubList)
assert.Nil(t, err)
defer resp.Body.Close()
assert.Greater(t, len(pubList), 0)
}
func TestServer_GetCurrentState_withSubscription(t *testing.T) {
// create subscription
sub := api.NewPubSub(
&types.URI{URL: url.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port), Path: fmt.Sprintf("%s%s", apPath, "dummy")}},
resource, "1.0")
data, err := json.Marshal(&sub)
assert.Nil(t, err)
assert.NotNil(t, data)
/// create new subscription
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "POST", fmt.Sprintf("http://localhost:%d%s%s", port, apPath, "subscriptions"), bytes.NewBuffer(data))
assert.Nil(t, err)
req.Header.Set("Content-Type", "application/json")
resp, err := server.HTTPClient.Do(req)
assert.Nil(t, err)
defer resp.Body.Close()
bodyBytes, err := io.ReadAll(resp.Body)
assert.Nil(t, err)
bodyString := string(bodyBytes)
log.Print(bodyString)
assert.Equal(t, http.StatusCreated, resp.StatusCode)
err = json.Unmarshal(bodyBytes, &ObjSub)
assert.Nil(t, err)
assert.NotEmpty(t, ObjSub.ID)
assert.NotEmpty(t, ObjSub.URILocation)
assert.NotEmpty(t, ObjSub.EndPointURI)
assert.NotEmpty(t, ObjSub.Resource)
assert.Equal(t, sub.Resource, ObjSub.Resource)
log.Infof("Subscription:\n%s", ObjSub.String())
// try getting event
time.Sleep(2 * time.Second)
req, err = http.NewRequestWithContext(ctx, "GET", fmt.Sprintf("http://localhost:%d%s%s/%s", port, apPath, ObjSub.Resource, "CurrentState"), nil)
assert.Nil(t, err)
req.Header.Set("Content-Type", "application/json")
resp, err = server.HTTPClient.Do(req)
assert.Nil(t, err)
defer resp.Body.Close()
s, err2 := io.ReadAll(resp.Body)
assert.Nil(t, err2)
log.Infof("tedt %s ", string(s))
assert.Equal(t, http.StatusOK, resp.StatusCode)
// Delete All Subscriptions
req, err = http.NewRequestWithContext(ctx, "DELETE", fmt.Sprintf("http://localhost:%d%s%s", port, apPath, "subscriptions"), nil)
assert.Nil(t, err)
req.Header.Set("Content-Type", "application/json")
resp, err = server.HTTPClient.Do(req)
assert.Nil(t, err)
defer resp.Body.Close()
}
func TestServer_GetCurrentState_withoutSubscription(t *testing.T) {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// try getting event
time.Sleep(2 * time.Second)
req, err := http.NewRequestWithContext(ctx, "GET", fmt.Sprintf("http://localhost:%d%s%s/%s", port, apPath, resourceNoneSubscribed, "CurrentState"), nil)
assert.Nil(t, err)
req.Header.Set("Content-Type", "application/json")
resp, err := server.HTTPClient.Do(req)
assert.Nil(t, err)
defer resp.Body.Close()
s, err2 := io.ReadAll(resp.Body)
assert.Nil(t, err2)
log.Infof("tedt %s ", string(s))
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
}
func TestServer_TestPingStatusStatusCode(t *testing.T) {
req, err := http.NewRequest("PUT", fmt.Sprintf("http://localhost:%d%s%s%s", port, apPath, "subscriptions/status/", ObjSub.ID), nil)
assert.Nil(t, err)
req.Header.Set("Content-Type", "application/json")
resp, err := server.HTTPClient.Do(req)
assert.Nil(t, err)
defer resp.Body.Close()
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
}
func TestServer_DeleteSubscription(t *testing.T) {
// Delete All Subscriptions
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "DELETE", fmt.Sprintf("http://localhost:%d%s%s", port, apPath, "subscriptions"), nil)
assert.Nil(t, err)
req.Header.Set("Content-Type", "application/json")
resp, err := server.HTTPClient.Do(req)
assert.Nil(t, err)
defer resp.Body.Close()
}
func TestServer_DeletePublisher(t *testing.T) {
// Delete All Publisher
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "DELETE", fmt.Sprintf("http://localhost:%d%s%s", port, apPath, "publishers"), nil)
assert.Nil(t, err)
req.Header.Set("Content-Type", "application/json")
resp, err := server.HTTPClient.Do(req)
assert.Nil(t, err)
defer resp.Body.Close()
}
func TestServer_GetNonExistingPublisher(t *testing.T) {
// Get Just created Publisher
req, err := http.NewRequest("GET", fmt.Sprintf("http://localhost:%d%s%s/%s", port, apPath, "publishers", ObjPub.ID), nil)
assert.Nil(t, err)
req.Header.Set("Content-Type", "application/json")
resp, err := server.HTTPClient.Do(req)
assert.Nil(t, err)
defer resp.Body.Close()
assert.Equal(t, resp.StatusCode, http.StatusBadRequest)
assert.Nil(t, err)
}
func TestServer_GetNonExistingSubscription(t *testing.T) {
// Get Just Created Subscription
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", fmt.Sprintf("http://localhost:%d%s%s/%s", port, apPath, "subscriptions", ObjSub.ID), nil)
assert.Nil(t, err)
req.Header.Set("Content-Type", "application/json")
resp, err := server.HTTPClient.Do(req)
assert.Nil(t, err)
defer resp.Body.Close()
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
}
func TestServer_TestDummyStatusCode(t *testing.T) {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "POST", fmt.Sprintf("http://localhost:%d%s%s", port, apPath, "dummy"), nil)
assert.Nil(t, err)
req.Header.Set("Content-Type", "application/json")
resp, err := server.HTTPClient.Do(req)
assert.Nil(t, err)
defer resp.Body.Close()
assert.Equal(t, http.StatusNoContent, resp.StatusCode)
}
func TestServer_KillAndRecover(t *testing.T) {
server.Shutdown()
time.Sleep(2 * time.Second)
// CHECK URL IS UP
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", fmt.Sprintf("http://localhost:%d%s%s", port, apPath, "health"), nil)
assert.Nil(t, err)
req.Header.Set("Content-Type", "application/json")
resp, err := server.HTTPClient.Do(req)
assert.Nil(t, err)
defer resp.Body.Close()
assert.Equal(t, http.StatusOK, resp.StatusCode)
}
// New get new rest client
func NewRestClient() *Rest {
return &Rest{
client: http.Client{
Timeout: 1 * time.Second,
},
}
}
func publishEvent(e event.Event) {
//create publisher
url := &types.URI{URL: url.URL{Scheme: "http",
Host: fmt.Sprintf("localhost:%d", port),
Path: fmt.Sprintf("%s%s", apPath, "create/event")}}
rc := NewRestClient()
err := rc.PostEvent(url, e)
if err != nil {
log.Errorf("error publishing events %v to url %s", err, url.String())
} else {
log.Debugf("published event %s", e.ID)
}
}
func Test_MultiplePost(t *testing.T) {
pub := pubsub.PubSub{
ID: "",
EndPointURI: &types.URI{URL: url.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port), Path: fmt.Sprintf("%s%s", apPath, "dummy")}},
Resource: resource,
}
pubData, err := json.Marshal(&pub)
assert.Nil(t, err)
assert.NotNil(t, pubData)
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "POST", fmt.Sprintf("http://localhost:%d%s%s", port, apPath, "publishers"), bytes.NewBuffer(pubData))
assert.Nil(t, err)
req.Header.Set("Content-Type", "application/json")
resp, err := server.HTTPClient.Do(req)
assert.Nil(t, err)
defer func() {
if resp != nil {
resp.Body.Close()
}
}()
pubBodyBytes, err := io.ReadAll(resp.Body)
assert.Nil(t, err)
err = json.Unmarshal(pubBodyBytes, &ObjPub)
assert.Nil(t, err)
assert.Equal(t, http.StatusCreated, resp.StatusCode)
assert.NotEmpty(t, ObjPub.ID)
assert.NotEmpty(t, ObjPub.URILocation)
assert.NotEmpty(t, ObjPub.EndPointURI)
assert.NotEmpty(t, ObjPub.Resource)
assert.Equal(t, pub.Resource, ObjPub.Resource)
log.Infof("publisher \n%s", ObjPub.String())
cneEvent := v1event.CloudNativeEvent()
cneEvent.SetID(ObjPub.ID)
cneEvent.Type = string(ptp.PtpStateChange)
cneEvent.SetTime(types.Timestamp{Time: time.Now().UTC()}.Time)
cneEvent.SetDataContentType(event.ApplicationJSON)
data := event.Data{
Version: "event",
Values: []event.DataValue{{
Resource: "test",
DataType: event.NOTIFICATION,
ValueType: event.ENUMERATION,
Value: ptp.ACQUIRING_SYNC,
},
},
}
data.SetVersion("v1") //nolint:errcheck
cneEvent.SetData(data)
for i := 0; i < 5; i++ {
go publishEvent(cneEvent)
}
time.Sleep(2 * time.Second)
}
func TestServer_End(*testing.T) {
os.Remove("pub.json")
os.Remove("sub.json")
close(eventOutCh)
close(closeCh)
}
// Rest client to make http request
type Rest struct {
client http.Client
}
// Post post with data
func (r *Rest) Post(url *types.URI, data []byte) int {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
request, err := http.NewRequestWithContext(ctx, "POST", url.String(), bytes.NewBuffer(data))
if err != nil {
log.Errorf("error creating post request %v", err)
return http.StatusBadRequest
}
request.Header.Set("content-type", "application/json")
response, err := r.client.Do(request)
if err != nil {
log.Errorf("error in post response %v", err)
return http.StatusBadRequest
}
if response.Body != nil {
defer response.Body.Close()
// read any content and print
body, readErr := io.ReadAll(response.Body)
if readErr == nil && len(body) > 0 {
log.Debugf("%s return response %s\n", url.String(), string(body))
}
}
return response.StatusCode
}
// New get new rest client
func New() *Rest {
return &Rest{
client: http.Client{
Timeout: 1 * time.Second,
},
}
}
// PostEvent post an event to the give url and check for error
func (r *Rest) PostEvent(url *types.URI, e event.Event) error {
b, err := json.Marshal(e)
if err != nil {
log.Errorf("error marshalling event %v", e)
return err
}
if status := r.Post(url, b); status == http.StatusBadRequest {
return fmt.Errorf("post returned status %d", status)
}
return nil
}