sms.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package dao
  2. import (
  3. "net/http"
  4. "net/url"
  5. "strconv"
  6. "time"
  7. "go-common/library/log"
  8. )
  9. const _smsURL = "http://ops-mng.bilibili.co/api/sendsms"
  10. type sms struct {
  11. d *Dao
  12. client *http.Client
  13. lastTime int64
  14. interval int64
  15. params *url.Values
  16. }
  17. func newSMS(d *Dao) (s *sms) {
  18. s = &sms{
  19. d: d,
  20. client: &http.Client{},
  21. lastTime: time.Now().Unix() - d.c.SMS.Interval, //如果不想让初始化的时候告警,把减号去掉
  22. interval: d.c.SMS.Interval,
  23. params: &url.Values{
  24. "phone": []string{d.c.SMS.Phone},
  25. "token": []string{d.c.SMS.Token},
  26. },
  27. }
  28. return
  29. }
  30. func (d *Dao) SendSMS(msg string) (err error) {
  31. if !d.sms.IntervalCheck() {
  32. log.Error("发短信太频繁啦, msg:%s", msg)
  33. return
  34. }
  35. if err = d.sms.Send(msg); err != nil {
  36. log.Error("发短信失败, msg:%s, error(%v)", msg, err)
  37. }
  38. return
  39. }
  40. func (sms *sms) Send(msg string) (err error) {
  41. var req *http.Request
  42. sms.params.Set("message", msg)
  43. if req, err = http.NewRequest("GET", _smsURL+"?"+sms.params.Encode(), nil); err != nil {
  44. return
  45. }
  46. req.Header.Set("x1-bilispy-timeout", strconv.FormatInt(int64(time.Duration(1)/time.Millisecond), 10))
  47. if _, err = sms.client.Do(req); err != nil {
  48. log.Error("ops-mng sendsms url(%s) error(%v)", _smsURL+"?"+sms.params.Encode(), err)
  49. }
  50. return
  51. }
  52. // IntervalCheck accessible or not to send msg at present time
  53. func (sms *sms) IntervalCheck() (send bool) {
  54. now := time.Now().Unix()
  55. if (now - sms.lastTime) >= sms.interval {
  56. send = true
  57. sms.lastTime = now
  58. } else {
  59. send = false
  60. }
  61. return
  62. }