/
httpreportsender.go
61 lines (53 loc) · 1.42 KB
/
httpreportsender.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
package v1
import (
"fmt"
"io"
"net/http"
"time"
httputils "github.com/armosec/utils-go/httputils"
)
type IHttpSender interface {
Send(serverURL string, headers map[string]string, reqBody []byte) (int, string, error)
}
type HttpReportSender struct {
httpClient httputils.IHttpClient
}
// Send sends an HTTP request to a server and returns the HTTP status code, return message, and any errors.
func (s *HttpReportSender) Send(serverURL string, headers map[string]string, reqBody []byte) (int, string, error) {
var resp *http.Response
var err error
var bodyAsStr string
for i := 0; i < MAX_RETRIES; i++ {
resp, err = httputils.HttpPost(s.httpClient, serverURL, headers, reqBody)
bodyAsStr = "body could not be fetched"
retry := err != nil
if resp != nil {
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
retry = true
}
if resp.Body != nil {
body, err := io.ReadAll(resp.Body)
if err == nil {
bodyAsStr = string(body)
}
resp.Body.Close()
}
}
if !retry {
break
}
if i == MAX_RETRIES-1 {
return 500, "", err
}
time.Sleep(RETRY_DELAY)
}
if resp == nil {
return 500, bodyAsStr, fmt.Errorf("failed to send report, empty response: %w", err)
}
return resp.StatusCode, bodyAsStr, nil
}
type HttpReportSenderMock struct {
}
func (sm *HttpReportSenderMock) Send(serverURL string, headers map[string]string, reqBody []byte) (int, string, error) {
return 200, "ok", nil
}