package gogs
import (
"encoding/json"
"fmt"
"io"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/levigross/grequests"
)
func GetMessage(c *gin.Context) {
body, err := io.ReadAll(c.Request.Body)
if err != nil {
c.JSON(500, gin.H{"error": "无法读取请求体"})
return
}
var pushEvent PushEvent
err = json.Unmarshal(body, &pushEvent)
if err != nil {
c.JSON(400, gin.H{"error": "JSON 解析错误"})
return
}
var times string
var info string
var author string
// var link string
// var timestamp int64
// var sign string
// now := time.Now()
// 获取时间戳(秒)
// timestamp = now.Unix()
for _, commit := range pushEvent.Commits {
// 将时间字符串解析为时间对象
timeObj, err := time.Parse(time.RFC3339, commit.Timestamp)
if err != nil {
fmt.Println("时间解析错误:", err)
continue
}
// 格式化时间为 需要加8小时
formattedTime := timeObj.Add(time.Hour * 8).Format("2006-01-02 15:04:05")
times = formattedTime
info = commit.Message
// link = commit.URL
author = commit.Author.Name
}
// 字符串截取去掉http://gogs.ainets.net/
HTMLURL := pushEvent.Repository.HTMLURL[23:]
if strings.HasPrefix(pushEvent.Ref, "refs/heads/") {
// 推送代码到分支
pushWx(author, "推送了代码", HTMLURL, info, times)
}
// if strings.HasPrefix(pushEvent.Ref, "refs/tags/") {
// // 创建了一个新的标签
// // pushWx(author, "将代码推至", pushEvent.Repository.HTMLURL )
// }
// pushWx(author)
c.Set("res_data", "ok")
}
// 对企微推送gogs事件
func pushWx(author string, label string, HTMLURL string, info string, times string) {
wxUrl := "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=d6a728ad-6cfb-4eb3-aa51-6a34ab671329"
msg := fmt.Sprintf(`
%s %s %s
> 目标仓库:%s
> 推送时间:%s
`, author, label, info, HTMLURL, times)
// 对象
type MarkdownContent struct {
Content string `json:"content"`
}
ro := &grequests.RequestOptions{
JSON: struct {
MsgType string `json:"msgtype"`
Markdown MarkdownContent `json:"markdown"`
}{
MsgType: "markdown",
Markdown: MarkdownContent{
Content: msg,
},
},
}
// 发送请求
grequests.Post(wxUrl, ro)
}