github.com/aporeto-inc/trireme-lib@v10.358.0+incompatible/monitor/remoteapi/client/client.go (about)

     1  package client
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"encoding/json"
     7  	"fmt"
     8  	"io/ioutil"
     9  	"net"
    10  	"net/http"
    11  	"time"
    12  
    13  	"go.aporeto.io/enforcerd/trireme-lib/common"
    14  )
    15  
    16  type dialContextFunc func(ctx context.Context, network, address string) (net.Conn, error)
    17  
    18  // SendRequest sends a request to the remote.
    19  // TODO: Add retries
    20  func (c *Client) SendRequest(event *common.EventInfo) error {
    21  
    22  	httpc := http.Client{
    23  		Transport: &http.Transport{
    24  			DialContext:     c.getDialContext(),
    25  			MaxIdleConns:    10,
    26  			IdleConnTimeout: 10 * time.Second,
    27  		},
    28  	}
    29  
    30  	b := new(bytes.Buffer)
    31  	if err := json.NewEncoder(b).Encode(event); err != nil {
    32  		return fmt.Errorf("Unable to encode message: %s", err)
    33  	}
    34  
    35  	resp, err := httpc.Post("http://unix", "application/json", b)
    36  	if err != nil {
    37  		return err
    38  	}
    39  	defer resp.Body.Close() // nolint
    40  
    41  	if resp.StatusCode == http.StatusAccepted {
    42  		return nil
    43  	}
    44  
    45  	errorBuffer, err := ioutil.ReadAll(resp.Body)
    46  	if err != nil {
    47  		return fmt.Errorf("Invalid request: %s", err)
    48  	}
    49  
    50  	return fmt.Errorf("Invalid request : %s", string(errorBuffer))
    51  }