另客网go项目公用的代码库

notification.go 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package hooks
  2. import (
  3. "fmt"
  4. "github.com/sirupsen/logrus"
  5. )
  6. var linkClient *Client
  7. type NotificationHook struct {
  8. Project *Project
  9. Maintainers []*Maintainer
  10. NS *NotificationService
  11. }
  12. type Project struct {
  13. Name string
  14. Domain string
  15. }
  16. type Maintainer struct {
  17. Name string
  18. Email string
  19. }
  20. type NotificationService struct {
  21. Addr string
  22. Port int
  23. }
  24. func DefaultMaintainers() []*Maintainer {
  25. return []*Maintainer{
  26. {
  27. Name: "Paul",
  28. Email: "paul@links123.com",
  29. },
  30. {
  31. Name: "Adam",
  32. Email: "adam@links123.com",
  33. },
  34. {
  35. Name: "Whao",
  36. Email: "whao@links123.com",
  37. },
  38. {
  39. Name: "Slate",
  40. Email: "slate@links123.com",
  41. },
  42. }
  43. }
  44. func DefaultNotificationService() *NotificationService {
  45. return &NotificationService{
  46. Addr: "127.0.0.1",
  47. Port: 8085,
  48. }
  49. }
  50. func (nh *NotificationHook) Fire(entry *logrus.Entry) error {
  51. return notify(nh, entry)
  52. }
  53. func (nh *NotificationHook) Levels() []logrus.Level {
  54. return []logrus.Level{
  55. logrus.ErrorLevel,
  56. logrus.FatalLevel,
  57. logrus.PanicLevel,
  58. }
  59. }
  60. func NewNotificationHook(project *Project, maintainers []*Maintainer, ns *NotificationService) (*NotificationHook, error) {
  61. if project == nil {
  62. return nil, fmt.Errorf("project is required")
  63. }
  64. if maintainers == nil {
  65. return nil, fmt.Errorf("maintainers muest not be blank")
  66. }
  67. if ns == nil {
  68. return nil, fmt.Errorf("notification service is required")
  69. }
  70. if linkClient == nil {
  71. linkClient = NewClient(ns.Addr, ns.Port)
  72. }
  73. return &NotificationHook{Project: project, Maintainers: maintainers, NS: ns}, nil
  74. }
  75. func notify(nh *NotificationHook, entry *logrus.Entry) error {
  76. var emails []string
  77. for _, m := range nh.Maintainers {
  78. emails = append(emails, m.Email)
  79. }
  80. _, err := defaultClient.Notify(&NotifyRequest{
  81. Project: nh.Project.Name,
  82. Maintainers: emails,
  83. Message: entry.Message,
  84. Time: entry.Time.Format("2006-02-01 15:04:05"),
  85. })
  86. return err
  87. }