noticer: 增加 http 发送通知接口

pull/1/head
miraclesu 8 years ago
parent 4059ac9bc6
commit 75c4519565

@ -35,10 +35,17 @@ func main() {
}
if conf.Config.Mail.Enable {
noticer, err := models.NewMail(10 * time.Second)
if err != nil {
log.Error(err.Error())
return
var noticer models.Noticer
if len(conf.Config.Mail.HttpAPI) > 0 {
noticer = &models.HttpAPI{}
} else {
mailer, err := models.NewMail(10 * time.Second)
if err != nil {
log.Error(err.Error())
return
}
noticer = mailer
}
go models.StartNoticer(noticer)
}

@ -81,7 +81,7 @@ type MailConf struct {
Enable bool
To []string
// 如果配置,则按 http api 方式发送,否则按 smtp 方式发送
HttpApi string
HttpAPI string
// 如果此时间段内没有邮件发送,则关闭 SMTP 连接,单位/秒
Keepalive int64
*gomail.Dialer

@ -1,8 +1,11 @@
package models
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
client "github.com/coreos/etcd/clientv3"
@ -73,7 +76,7 @@ func (m *Mail) Serve() {
m.timer.Reset(time.Duration(m.cf.Keepalive) * time.Second)
if !m.open {
if m.sc, err = m.cf.Dialer.Dial(); err != nil {
log.Warnf("send msg[%+v] err: %s", msg, err.Error())
log.Warnf("smtp send msg[%+v] err: %s", msg, err.Error())
continue
}
m.open = true
@ -85,7 +88,7 @@ func (m *Mail) Serve() {
sm.SetHeader("Subject", msg.Subject)
sm.SetBody("text/plain", msg.Body)
if err := gomail.Send(m.sc, sm); err != nil {
log.Warnf("send msg[%+v] err: %s", msg, err.Error())
log.Warnf("smtp send msg[%+v] err: %s", msg, err.Error())
}
case <-m.timer.C:
if m.open {
@ -104,6 +107,43 @@ func (m *Mail) Send(msg *Message) {
m.msgChan <- msg
}
type HttpAPI struct{}
func (h *HttpAPI) Serve() {}
func (h *HttpAPI) Send(msg *Message) {
body, err := json.Marshal(msg)
if err != nil {
log.Warnf("http api send msg[%+v] err: %s", msg, err.Error())
return
}
req, err := http.NewRequest("POST", conf.Config.Mail.HttpAPI, bytes.NewBuffer(body))
if err != nil {
return
}
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Warnf("http api send msg[%+v] err: %s", msg, err.Error())
return
}
defer resp.Body.Close()
if resp.StatusCode == 200 {
return
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Warnf("http api send msg[%+v] err: %s", msg, err.Error())
return
}
log.Warnf("http api send msg[%+v] err: %s", msg, string(data))
return
}
func StartNoticer(n Noticer) {
go n.Serve()
rch := DefalutClient.Watch(conf.Config.Noticer, client.WithPrefix())

Loading…
Cancel
Save