You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

hooks.go 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package hooks
  5. import (
  6. "encoding/json"
  7. "time"
  8. "github.com/gogits/gogs/modules/httplib"
  9. "github.com/gogits/gogs/modules/log"
  10. )
  11. // Hook task types.
  12. const (
  13. HTT_WEBHOOK = iota + 1
  14. HTT_SERVICE
  15. )
  16. type PayloadAuthor struct {
  17. Name string `json:"name"`
  18. Email string `json:"email"`
  19. }
  20. type PayloadCommit struct {
  21. Id string `json:"id"`
  22. Message string `json:"message"`
  23. Url string `json:"url"`
  24. Author *PayloadAuthor `json:"author"`
  25. }
  26. type PayloadRepo struct {
  27. Id int64 `json:"id"`
  28. Name string `json:"name"`
  29. Url string `json:"url"`
  30. Description string `json:"description"`
  31. Website string `json:"website"`
  32. Watchers int `json:"watchers"`
  33. Owner *PayloadAuthor `json:"author"`
  34. Private bool `json:"private"`
  35. }
  36. // Payload represents payload information of hook.
  37. type Payload struct {
  38. Secret string `json:"secret"`
  39. Ref string `json:"ref"`
  40. Commits []*PayloadCommit `json:"commits"`
  41. Repo *PayloadRepo `json:"repository"`
  42. Pusher *PayloadAuthor `json:"pusher"`
  43. }
  44. // HookTask represents hook task.
  45. type HookTask struct {
  46. Type int
  47. Url string
  48. *Payload
  49. ContentType int
  50. IsSsl bool
  51. }
  52. var (
  53. taskQueue = make(chan *HookTask, 1000)
  54. )
  55. // AddHookTask adds new hook task to task queue.
  56. func AddHookTask(t *HookTask) {
  57. taskQueue <- t
  58. }
  59. func init() {
  60. go handleQueue()
  61. }
  62. func handleQueue() {
  63. for {
  64. select {
  65. case t := <-taskQueue:
  66. // Only support JSON now.
  67. data, err := json.MarshalIndent(t.Payload, "", "\t")
  68. if err != nil {
  69. log.Error("hooks.handleQueue(json): %v", err)
  70. continue
  71. }
  72. _, err = httplib.Post(t.Url).SetTimeout(5*time.Second, 5*time.Second).
  73. Body(data).Response()
  74. if err != nil {
  75. log.Error("hooks.handleQueue: Fail to deliver hook: %v", err)
  76. continue
  77. }
  78. log.Info("Hook delivered: %s", string(data))
  79. }
  80. }
  81. }