/
client.go
51 lines (41 loc) · 1.03 KB
/
client.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
package client
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"time"
"go.aporeto.io/trireme-lib/common"
)
type dialContextFunc func(ctx context.Context, network, address string) (net.Conn, error)
// SendRequest sends a request to the remote.
// TODO: Add retries
func (c *Client) SendRequest(event *common.EventInfo) error {
httpc := http.Client{
Transport: &http.Transport{
DialContext: c.getDialContext(),
MaxIdleConns: 10,
IdleConnTimeout: 10 * time.Second,
},
}
b := new(bytes.Buffer)
if err := json.NewEncoder(b).Encode(event); err != nil {
return fmt.Errorf("Unable to encode message: %s", err)
}
resp, err := httpc.Post("http://unix", "application/json", b)
if err != nil {
return err
}
defer resp.Body.Close() // nolint
if resp.StatusCode == http.StatusAccepted {
return nil
}
errorBuffer, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("Invalid request: %s", err)
}
return fmt.Errorf("Invalid request : %s", string(errorBuffer))
}