// Package notify 通知渠道(Day 27):企微/钉钉群机器人 webhook 推送。 // // 语义:Notifier 无状态可并发复用;Send 失败返回错误由调用方决定重试策略 // (余额预警服务在冷却期内不写 LastAlertAt,下轮扫描自动重试)。 package notify import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" "strings" "time" ) // Notifier 通知渠道抽象(测试以假实现注入)。 type Notifier interface { Send(ctx context.Context, title, content string) error } // httpCli 包级复用(短超时,避免告警拖垮调度循环)。 var httpCli = &http.Client{Timeout: 5 * time.Second} // Webhook 企微/钉钉群机器人(Type: wechat|dingtalk;URL 为机器人地址)。 type Webhook struct { Type string URL string } // NewWebhook 构造;typ 为空时默认 wechat。 func NewWebhook(typ, url string) *Webhook { if typ == "" { typ = "wechat" } return &Webhook{Type: typ, URL: url} } // payload 按渠道组装消息体。 func (w *Webhook) payload(title, content string) any { text := title + "\n" + content switch strings.ToLower(w.Type) { case "dingtalk": return map[string]any{"msgtype": "text", "text": map[string]string{"content": text}} default: // wechat return map[string]any{"msgtype": "markdown", "markdown": map[string]string{"content": text}} } } // Send POST JSON 到机器人地址;非 2xx 或业务 errcode≠0 视为失败。 func (w *Webhook) Send(ctx context.Context, title, content string) error { if w.URL == "" { return fmt.Errorf("notify: webhook 地址为空(%s)", w.Type) } body, err := json.Marshal(w.payload(title, content)) if err != nil { return err } req, err := http.NewRequestWithContext(ctx, http.MethodPost, w.URL, bytes.NewReader(body)) if err != nil { return err } req.Header.Set("Content-Type", "application/json") resp, err := httpCli.Do(req) if err != nil { return fmt.Errorf("notify: webhook 请求失败: %w", err) } defer func() { _ = resp.Body.Close() }() raw, _ := io.ReadAll(io.LimitReader(resp.Body, 512)) if resp.StatusCode < 200 || resp.StatusCode >= 300 { return fmt.Errorf("notify: webhook 状态 %d: %s", resp.StatusCode, string(raw)) } // 企微/钉钉均以 errcode 表达业务失败 if s := string(raw); strings.Contains(s, `"errcode":0`) || strings.TrimSpace(s) == "" { return nil } else if strings.Contains(s, `"errcode"`) { return fmt.Errorf("notify: webhook 业务失败: %s", s) } return nil } // Multi 聚合多渠道:逐个发送,全部失败才返回错误(部分成功即视为通知已达)。 type Multi []Notifier // Send 逐渠道发送,聚合错误。 func (m Multi) Send(ctx context.Context, title, content string) error { var errs []string for _, n := range m { if err := n.Send(ctx, title, content); err != nil { errs = append(errs, err.Error()) } } if len(errs) == len(m) && len(m) > 0 { return fmt.Errorf("notify: 全部渠道失败: %s", strings.Join(errs, "; ")) } return nil }