mattermost.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package providers
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "git.wenlab.co/joe/beaconfire"
  7. )
  8. const MATTERMOST_NAME = "mattermost"
  9. type OptionsMattermost struct {
  10. Url string
  11. HookId string
  12. IconUrl string
  13. BotName string
  14. To []string
  15. }
  16. type mattermost struct {
  17. opt *OptionsMattermost
  18. }
  19. var _ beaconfire.BeaconFire = &mattermost{}
  20. func NewMattermost(opt *OptionsMattermost) *mattermost {
  21. return &mattermost{
  22. opt: opt,
  23. }
  24. }
  25. func (c mattermost) Name() string {
  26. return MATTERMOST_NAME
  27. }
  28. type message struct {
  29. Channel string `json:"channel,omitempty"`
  30. Username string `json:"username,omitempty"`
  31. IconUrl string `json:"icon_url,omitempty"`
  32. Text string `json:"text"`
  33. }
  34. func (c *mattermost) Send(bp *beaconfire.BeaconParam) error {
  35. if len(c.opt.To) <= 0 {
  36. return beaconfire.ErrNoReceiver
  37. }
  38. u := fmt.Sprintf("%s/hooks/%s", c.opt.Url, c.opt.HookId)
  39. for _, channel := range c.opt.To {
  40. m := message{
  41. Channel: channel,
  42. Username: c.opt.BotName,
  43. IconUrl: c.opt.IconUrl,
  44. Text: bp.Content,
  45. }
  46. msg, err := json.Marshal(m)
  47. if err != nil {
  48. return err
  49. }
  50. res, err := beaconfire.PostJson(u, msg)
  51. if err != nil {
  52. return err
  53. }
  54. var r struct {
  55. Ok bool `json:"ok"`
  56. ErrorCode int `json:"error_code"`
  57. Description string `json:"description"`
  58. }
  59. err = json.Unmarshal(res, &r)
  60. if nil != err {
  61. return err
  62. }
  63. if !r.Ok {
  64. return errors.New(r.Description)
  65. }
  66. }
  67. return nil
  68. }