1
0

jianliao.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package logs
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "net/url"
  7. "time"
  8. )
  9. // JLWriter implements beego LoggerInterface and is used to send jiaoliao webhook
  10. type JLWriter struct {
  11. AuthorName string `json:"authorname"`
  12. Title string `json:"title"`
  13. WebhookURL string `json:"webhookurl"`
  14. RedirectURL string `json:"redirecturl,omitempty"`
  15. ImageURL string `json:"imageurl,omitempty"`
  16. Level int `json:"level"`
  17. }
  18. // newJLWriter create jiaoliao writer.
  19. func newJLWriter() Logger {
  20. return &JLWriter{Level: LevelTrace}
  21. }
  22. // Init JLWriter with json config string
  23. func (s *JLWriter) Init(jsonconfig string) error {
  24. err := json.Unmarshal([]byte(jsonconfig), s)
  25. if err != nil {
  26. return err
  27. }
  28. return nil
  29. }
  30. // WriteMsg write message in smtp writer.
  31. // it will send an email with subject and only this message.
  32. func (s *JLWriter) WriteMsg(when time.Time, msg string, level int) error {
  33. if level > s.Level {
  34. return nil
  35. }
  36. text := fmt.Sprintf("%s %s", when.Format("2006-01-02 15:04:05"), msg)
  37. form := url.Values{}
  38. form.Add("authorName", s.AuthorName)
  39. form.Add("title", s.Title)
  40. form.Add("text", text)
  41. if s.RedirectURL != "" {
  42. form.Add("redirectUrl", s.RedirectURL)
  43. }
  44. if s.ImageURL != "" {
  45. form.Add("imageUrl", s.ImageURL)
  46. }
  47. resp, err := http.PostForm(s.WebhookURL, form)
  48. if err != nil {
  49. return err
  50. }
  51. defer resp.Body.Close()
  52. if resp.StatusCode != http.StatusOK {
  53. return fmt.Errorf("Post webhook failed %s %d", resp.Status, resp.StatusCode)
  54. }
  55. return nil
  56. }
  57. // Flush implementing method. empty.
  58. func (s *JLWriter) Flush() {
  59. return
  60. }
  61. // Destroy implementing method. empty.
  62. func (s *JLWriter) Destroy() {
  63. return
  64. }
  65. func init() {
  66. Register(AdapterJianLiao, newJLWriter)
  67. }