webhook.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package entity
  2. import (
  3. "backup-x/util"
  4. "encoding/json"
  5. "fmt"
  6. "log"
  7. "net/http"
  8. "net/url"
  9. "strings"
  10. "time"
  11. )
  12. // Webhook Webhook
  13. type Webhook struct {
  14. WebhookURL string
  15. WebhookRequestBody string
  16. }
  17. // ExecWebhook 添加或更新IPv4/IPv6记录
  18. func (webhook Webhook) ExecWebhook(result BackupResult) {
  19. if webhook.WebhookURL != "" {
  20. // 成功和失败都要触发webhook
  21. method := "GET"
  22. postPara := ""
  23. contentType := "application/x-www-form-urlencoded"
  24. if webhook.WebhookRequestBody != "" {
  25. method = "POST"
  26. postPara = webhook.replaceBody(result)
  27. if json.Valid([]byte(postPara)) {
  28. contentType = "application/json"
  29. }
  30. }
  31. requestURL := webhook.replaceURL(result)
  32. u, err := url.Parse(requestURL)
  33. if err != nil {
  34. log.Println("Webhook配置中的URL不正确")
  35. return
  36. }
  37. req, err := http.NewRequest(method, fmt.Sprintf("%s://%s%s?%s", u.Scheme, u.Host, u.Path, u.Query().Encode()), strings.NewReader(postPara))
  38. if err != nil {
  39. log.Println("创建Webhook请求异常, Err:", err)
  40. return
  41. }
  42. req.Header.Add("content-type", contentType)
  43. clt := http.Client{}
  44. clt.Timeout = 30 * time.Second
  45. resp, err := clt.Do(req)
  46. body, err := util.GetHTTPResponseOrg(resp, requestURL, err)
  47. if err == nil {
  48. log.Println(fmt.Sprintf("Webhook调用成功, 返回数据: %s", string(body)))
  49. } else {
  50. log.Println(fmt.Sprintf("Webhook调用失败,Err:%s", err))
  51. }
  52. }
  53. }
  54. // replaceURL 替换url
  55. func (webhook Webhook) replaceURL(result BackupResult) (newBody string) {
  56. newBody = strings.ReplaceAll(webhook.WebhookURL, "#{projectName}", result.ProjectName)
  57. newBody = strings.ReplaceAll(newBody, "#{fileName}", result.FileName)
  58. newBody = strings.ReplaceAll(newBody, "#{fileSize}", result.FileSize)
  59. newBody = strings.ReplaceAll(newBody, "#{result}", result.Result)
  60. return newBody
  61. }
  62. // replaceBody 替换body
  63. func (webhook Webhook) replaceBody(result BackupResult) (newURL string) {
  64. newURL = strings.ReplaceAll(webhook.WebhookRequestBody, "#{projectName}", result.ProjectName)
  65. newURL = strings.ReplaceAll(newURL, "#{fileName}", result.FileName)
  66. newURL = strings.ReplaceAll(newURL, "#{fileSize}", result.FileSize)
  67. newURL = strings.ReplaceAll(newURL, "#{result}", result.Result)
  68. return newURL
  69. }