12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package utils
  2. import (
  3. "bytes"
  4. "fmt"
  5. "net/http"
  6. "strings"
  7. "sync"
  8. "github.com/astaxie/beego/config"
  9. )
  10. // SMSEngine 短信
  11. type SMSEngine struct {
  12. url string
  13. method string
  14. contentType string
  15. setting config.Configer
  16. }
  17. var defaultSMS *SMSEngine
  18. var mtx = new(sync.Mutex)
  19. // ResetSMSEngine 重置引擎
  20. func ResetSMSEngine(conf config.Configer) {
  21. mtx.Lock()
  22. defer mtx.Unlock()
  23. newAPIURL := conf.String("url")
  24. if defaultSMS == nil || defaultSMS.url != newAPIURL {
  25. defaultSMS = &SMSEngine{
  26. url: conf.String("url"),
  27. method: strings.ToUpper(conf.String("method")),
  28. contentType: conf.String("contentType"),
  29. setting: conf,
  30. }
  31. }
  32. }
  33. // SendSMS 发送短信
  34. func SendSMS(smsType, tel string, messages ...string) {
  35. go func() {
  36. if defaultSMS == nil {
  37. LogError("没有成功初始化短信引擎")
  38. return
  39. }
  40. // 接口内容
  41. messageTpl := defaultSMS.setting.String(smsType + "::message")
  42. // 发送消息
  43. message := strings.Join(messages, `","`)
  44. if message != "" {
  45. message = fmt.Sprintf(`"%s"`, message)
  46. }
  47. // 接口 data
  48. data := bytes.NewBuffer([]byte(fmt.Sprintf(messageTpl, tel, message)))
  49. // 暂时只支持 post 发送数据
  50. if defaultSMS.method == http.MethodPost {
  51. resp, err := http.Post(defaultSMS.url, defaultSMS.contentType, data)
  52. if err != nil {
  53. LogError("短信发送错误: " + err.Error())
  54. }
  55. if resp.StatusCode != http.StatusOK {
  56. LogError("短信发送失败: " + resp.Status)
  57. }
  58. }
  59. }()
  60. }