-
Notifications
You must be signed in to change notification settings - Fork 72
/
http_callback.go
66 lines (51 loc) · 1.17 KB
/
http_callback.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
package ghostferry
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"github.com/sirupsen/logrus"
)
type HTTPCallback struct {
URI string
Payload string
}
func (h HTTPCallback) Post(client *http.Client) error {
if h.URI == "" {
return nil
}
payload := map[string]interface{}{"Payload": h.Payload}
return postCallback(client, h.URI, payload)
}
func postCallback(client *http.Client, uri string, body interface{}) error {
buf := bytes.Buffer{}
err := json.NewEncoder(&buf).Encode(body)
if err != nil {
return err
}
logger := logrus.WithFields(logrus.Fields{
"tag": "http-callback",
"uri": uri,
})
logger.Debug("sending callback")
res, err := client.Post(uri, "application/json", &buf)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode == 200 {
io.Copy(ioutil.Discard, res.Body)
return nil
}
resBody, err := ioutil.ReadAll(res.Body)
if err != nil {
logger.WithField("error", err).Errorf("error reading callback body")
}
logger.WithFields(logrus.Fields{
"status": res.StatusCode,
"body": string(resBody),
}).Errorf("callback not ok")
return fmt.Errorf("callback returned %s", res.Status)
}