added client for send msgs to alertmanager
This commit is contained in:
parent
ecdff721f8
commit
bc69f006f7
52
clients/alert_manager/client.go
Normal file
52
clients/alert_manager/client.go
Normal file
@ -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
|
||||
}
|
23
clients/alert_manager/client_test.go
Normal file
23
clients/alert_manager/client_test.go
Normal file
@ -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")
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user