feat(collectors) basic implementation of boring collectors; sender via http(s) to hard coded api route
This commit is contained in:
66
internal/sender/http.go
Normal file
66
internal/sender/http.go
Normal file
@@ -0,0 +1,66 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user