-
Notifications
You must be signed in to change notification settings - Fork 0
/
webhook.go
82 lines (69 loc) · 2.17 KB
/
webhook.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package main
import (
"bytes"
"fmt"
"github.com/Logiase/gomirai/message"
"github.com/labstack/echo/v4"
"io/ioutil"
"net/http"
"path"
"text/template"
)
//type Tag map[string]string
type GrafanaWebhookRequest struct {
//DashboardID int `json:"dashboardId"`
//EvalMatches []struct {
// Value int `json:"value"`
// Metric string `json:"metric"`
// Tags Tag `json:"tags"`
//} `json:"evalMatches"`
ImageURL string `json:"imageUrl"`
//Message string `json:"message" validate:"required"`
//OrgID int `json:"orgId"`
PanelID int `json:"panelId"`
RuleID int `json:"ruleId"`
RuleName string `json:"ruleName"`
RuleURL string `json:"ruleUrl" validate:"required"`
State string `json:"state"`
//Tags Tag `json:"tags"`
Title string `json:"title" validate:"required"`
}
func readTemplateFile(name string) string {
t, _ := ioutil.ReadFile(path.Join("templates", fmt.Sprintf("%s.tmpl", name)))
return string(t)
}
func webhookHandler(c echo.Context) error {
r := new(GrafanaWebhookRequest)
if err := c.Bind(r); err != nil {
return responseError(http.StatusBadRequest, "bind request failed", err)
}
if err := c.Validate(r); err != nil {
return responseError(http.StatusBadRequest, "request validation failed", err)
}
var messageTemplate string
switch r.State {
case GrafanaWebhookStateOK:
messageTemplate = readTemplateFile("state-ok")
case GrafanaWebhookStateAlerting:
messageTemplate = readTemplateFile("state-alerting")
default:
return c.NoContent(http.StatusOK)
}
msg := bytes.NewBufferString("")
err := template.Must(template.New("message").Parse(messageTemplate)).Execute(msg, r)
if err != nil {
return responseError(http.StatusInternalServerError, "failed to format message", err)
}
Log.Println("formatted plain message as", msg.String())
messages := []message.Message{
message.PlainMessage(msg.String()),
}
if r.ImageURL != "" {
messages = append(messages, message.ImageMessage("url", r.ImageURL))
}
err = botSendGroupMessage(Conf.QQ.Group, 0, messages...)
if err != nil {
return responseError(http.StatusInternalServerError, "failed to send message after consecutive retries", err)
}
return c.NoContent(http.StatusAccepted)
}