67 lines
1.1 KiB
Go
67 lines
1.1 KiB
Go
|
|
package sender
|
||
|
|
|
||
|
|
import (
|
||
|
|
"bytes"
|
||
|
|
"context"
|
||
|
|
"encoding/json"
|
||
|
|
"net/http"
|
||
|
|
"time"
|
||
|
|
|
||
|
|
"bugs.watch/agent/internal/aggregate"
|
||
|
|
)
|
||
|
|
|
||
|
|
type HTTPSender struct {
|
||
|
|
client *http.Client
|
||
|
|
endpoint string
|
||
|
|
}
|
||
|
|
|
||
|
|
func NewHTTPSender(endpoint string) *HTTPSender {
|
||
|
|
return &HTTPSender{
|
||
|
|
client: &http.Client{
|
||
|
|
Timeout: 5 * time.Second,
|
||
|
|
},
|
||
|
|
endpoint: endpoint,
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func (s *HTTPSender) Send(ctx context.Context, snap aggregate.Snapshot) error {
|
||
|
|
payload := SnapshotPayload{
|
||
|
|
Timestamp: snap.Timestamp,
|
||
|
|
CPUAvg: snap.CPUAvg,
|
||
|
|
MemAvg: snap.MemAvg,
|
||
|
|
DiskAvg: snap.DiskAvg,
|
||
|
|
Uptime: snap.Uptime,
|
||
|
|
}
|
||
|
|
|
||
|
|
body, err := json.Marshal(payload)
|
||
|
|
if err != nil {
|
||
|
|
return err
|
||
|
|
}
|
||
|
|
|
||
|
|
req, err := http.NewRequestWithContext(
|
||
|
|
ctx,
|
||
|
|
http.MethodPost,
|
||
|
|
s.endpoint,
|
||
|
|
bytes.NewReader(body),
|
||
|
|
)
|
||
|
|
if err != nil {
|
||
|
|
return err
|
||
|
|
}
|
||
|
|
|
||
|
|
req.Header.Set("Content-Type", "application/json")
|
||
|
|
|
||
|
|
resp, err := s.client.Do(req)
|
||
|
|
if err != nil {
|
||
|
|
return err
|
||
|
|
}
|
||
|
|
defer resp.Body.Close()
|
||
|
|
|
||
|
|
// We do not retry or branch yet.
|
||
|
|
// Any non-2xx is treated as a failure.
|
||
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||
|
|
return nil
|
||
|
|
}
|
||
|
|
|
||
|
|
return nil
|
||
|
|
}
|