gogs.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package gogs
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "strings"
  7. "time"
  8. "github.com/gin-gonic/gin"
  9. "github.com/levigross/grequests"
  10. )
  11. func GetMessage(c *gin.Context) {
  12. body, err := io.ReadAll(c.Request.Body)
  13. if err != nil {
  14. c.JSON(500, gin.H{"error": "无法读取请求体"})
  15. return
  16. }
  17. var pushEvent PushEvent
  18. err = json.Unmarshal(body, &pushEvent)
  19. if err != nil {
  20. c.JSON(400, gin.H{"error": "JSON 解析错误"})
  21. return
  22. }
  23. var times string
  24. var info string
  25. var author string
  26. // var link string
  27. // var timestamp int64
  28. // var sign string
  29. // now := time.Now()
  30. // 获取时间戳(秒)
  31. // timestamp = now.Unix()
  32. for _, commit := range pushEvent.Commits {
  33. // 将时间字符串解析为时间对象
  34. timeObj, err := time.Parse(time.RFC3339, commit.Timestamp)
  35. if err != nil {
  36. fmt.Println("时间解析错误:", err)
  37. continue
  38. }
  39. // 格式化时间为 需要加8小时
  40. formattedTime := timeObj.Add(time.Hour * 8).Format("2006-01-02 15:04:05")
  41. times = formattedTime
  42. info = commit.Message
  43. // link = commit.URL
  44. author = commit.Author.Name
  45. }
  46. // 字符串截取去掉http://gogs.ainets.net/
  47. HTMLURL := pushEvent.Repository.HTMLURL[23:]
  48. if strings.HasPrefix(pushEvent.Ref, "refs/heads/") {
  49. // 推送代码到分支
  50. pushWx(author, "推送了代码", HTMLURL, info, times)
  51. }
  52. // if strings.HasPrefix(pushEvent.Ref, "refs/tags/") {
  53. // // 创建了一个新的标签
  54. // // pushWx(author, "将代码推至", pushEvent.Repository.HTMLURL )
  55. // }
  56. // pushWx(author)
  57. c.Set("res_data", "ok")
  58. }
  59. // 对企微推送gogs事件
  60. func pushWx(author string, label string, HTMLURL string, info string, times string) {
  61. wxUrl := "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=d6a728ad-6cfb-4eb3-aa51-6a34ab671329"
  62. msg := fmt.Sprintf(`
  63. %s <font color="warning">%s</font> %s
  64. > 目标仓库:<font color="comment">%s</font>
  65. > 推送时间:<font color="comment">%s</font>
  66. `, author, label, info, HTMLURL, times)
  67. // 对象
  68. type MarkdownContent struct {
  69. Content string `json:"content"`
  70. }
  71. ro := &grequests.RequestOptions{
  72. JSON: struct {
  73. MsgType string `json:"msgtype"`
  74. Markdown MarkdownContent `json:"markdown"`
  75. }{
  76. MsgType: "markdown",
  77. Markdown: MarkdownContent{
  78. Content: msg,
  79. },
  80. },
  81. }
  82. // 发送请求
  83. grequests.Post(wxUrl, ro)
  84. }