diff --git a/clients/alert_manager/client.go b/clients/alert_manager/client.go new file mode 100644 index 0000000..909876f --- /dev/null +++ b/clients/alert_manager/client.go @@ -0,0 +1,52 @@ +package alert_manager + +import ( + "encoding/json" + "fmt" + "github.com/gofiber/fiber/v2" + "time" +) + +type Alert struct { + StartsAT time.Time `json:"startsAt"` + EndsAT time.Time `json:"endsAt"` + Annotations map[string]string `json:"annotations"` + Labels map[string]string `json:"labels"` + GeneratorURL string `json:"generatorURL"` +} + +type Client struct { + baseURL string + httpClient *fiber.Client +} + +func NewClient(baseURL string) *Client { + httpClient := fiber.AcquireClient() + return &Client{ + baseURL: baseURL, + httpClient: httpClient, + } +} + +func (c *Client) SendAlerts(alerts []Alert) error { + url := c.baseURL + "/api/v2/alerts" + + requestBody, err := json.Marshal(alerts) + if err != nil { + return err + } + + agent := c.httpClient.Post(url) + agent.Set("Content-Type", "application/json").Body(requestBody) + + statusCode, respBody, errs := agent.Bytes() + if len(errs) > 0 { + return fmt.Errorf("%v", errs) + } + + if statusCode != fiber.StatusOK { + return fmt.Errorf("invalid status code from alert manager: %d, response body:%s", statusCode, string(respBody)) + } + + return nil +} diff --git a/clients/alert_manager/client_test.go b/clients/alert_manager/client_test.go new file mode 100644 index 0000000..507d6a3 --- /dev/null +++ b/clients/alert_manager/client_test.go @@ -0,0 +1,23 @@ +package alert_manager + +import ( + "github.com/pioz/faker" + "github.com/stretchr/testify/assert" + "testing" + "time" +) + +func TestClient_SendAlerts(t *testing.T) { + client := NewClient("http://localhost:9093") + for i := 0; i < 50; i++ { + err := client.SendAlerts([]Alert{ + { + StartsAT: time.Now(), + Annotations: map[string]string{"Annotations": faker.String()}, + Labels: map[string]string{"Labels": faker.String()}, + GeneratorURL: "http://example.com", + }, + }) + assert.NoError(t, err, "received err from SendAlerts") + } +}