|
7 | 7 | "encoding/json"
|
8 | 8 | "errors"
|
9 | 9 | "fmt"
|
| 10 | + "io/ioutil" |
10 | 11 | "net/http"
|
11 | 12 | "strings"
|
12 | 13 |
|
@@ -50,6 +51,8 @@ func ToActioner(in interface{}) (Action, error) {
|
50 | 51 | a = &HTTP{}
|
51 | 52 | case "slack":
|
52 | 53 | a = &Slack{}
|
| 54 | + case "dingding": |
| 55 | + a = &DingDing{} |
53 | 56 | default:
|
54 | 57 | return Action{}, fmt.Errorf("unknown action type: %q", typ)
|
55 | 58 | }
|
@@ -142,3 +145,51 @@ func (s *Slack) Do(c context.Context) error {
|
142 | 145 | resp.Body.Close()
|
143 | 146 | return nil
|
144 | 147 | }
|
| 148 | + |
| 149 | +type DingDing struct { |
| 150 | + Text string `json:"text" mapstructure:"text"` |
| 151 | +} |
| 152 | + |
| 153 | +func (d *DingDing) Do(c context.Context) error { |
| 154 | + if config.Opts.DingDingWebhook == "" { |
| 155 | + return errors.New("DingDing Webhook not set in config") |
| 156 | + } |
| 157 | + |
| 158 | + if d.Text == "" { |
| 159 | + return errors.New("missing required field text in DingDing") |
| 160 | + } |
| 161 | + |
| 162 | + r, err := http.NewRequest("POST", config.Opts.DingDingWebhook, bytes.NewBufferString(d.Text)) |
| 163 | + if err != nil { |
| 164 | + return err |
| 165 | + } |
| 166 | + r.Header.Set("Content-Type", "application/json;charset=utf-8") |
| 167 | + |
| 168 | + |
| 169 | + resp, err := http.DefaultClient.Do(r) |
| 170 | + if err != nil { |
| 171 | + return err |
| 172 | + } |
| 173 | + |
| 174 | + defer resp.Body.Close() |
| 175 | + |
| 176 | + if resp.StatusCode < 200 || resp.StatusCode > 299 { |
| 177 | + return fmt.Errorf("non 2xx response code returned: %d", resp.StatusCode) |
| 178 | + } |
| 179 | + |
| 180 | + type response struct { |
| 181 | + ErrCode uint `json:"errcode"` |
| 182 | + ErrMsg string `json:"errmsg"` |
| 183 | + } |
| 184 | + var res response |
| 185 | + body, err := ioutil.ReadAll(resp.Body) |
| 186 | + if err != nil { |
| 187 | + return err |
| 188 | + } |
| 189 | + err = json.Unmarshal(body, &res) |
| 190 | + if res.ErrCode != 0 { |
| 191 | + return fmt.Errorf("response error: %s", res.ErrMsg) |
| 192 | + } |
| 193 | + return nil |
| 194 | + |
| 195 | +} |
0 commit comments