sms.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. // SendSMS .
  31. func (d *Dao) SendSMS(msg string) (err error) {
  32. if !d.sms.IntervalCheck() {
  33. log.Error("发短信太频繁啦, msg:%s", msg)
  34. return
  35. }
  36. if err = d.sms.Send(msg); err != nil {
  37. log.Error("发短信失败, msg:%s, error(%v)", msg, err)
  38. }
  39. return
  40. }
  41. func (sms *sms) Send(msg string) (err error) {
  42. var req *http.Request
  43. sms.params.Set("message", msg)
  44. if req, err = http.NewRequest("GET", _smsURL+"?"+sms.params.Encode(), nil); err != nil {
  45. return
  46. }
  47. req.Header.Set("x1-bilispy-timeout", strconv.FormatInt(int64(time.Duration(1)/time.Millisecond), 10))
  48. if _, err = sms.client.Do(req); err != nil {
  49. log.Error("ops-mng sendsms url(%s) error(%v)", _smsURL+"?"+sms.params.Encode(), err)
  50. }
  51. return
  52. }
  53. // IntervalCheck accessible or not to send msg at present time
  54. func (sms *sms) IntervalCheck() (send bool) {
  55. now := time.Now().Unix()
  56. if (now - sms.lastTime) >= sms.interval {
  57. send = true
  58. sms.lastTime = now
  59. } else {
  60. send = false
  61. }
  62. return
  63. }