hooks.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. // Payload represents payload information of hook.
  27. type Payload struct {
  28. Secret string `json:"secret"`
  29. Ref string `json:"ref"`
  30. Commits []*PayloadCommit `json:"commits"`
  31. Pusher *PayloadAuthor `json:"pusher"`
  32. }
  33. // HookTask represents hook task.
  34. type HookTask struct {
  35. Type int
  36. Url string
  37. *Payload
  38. ContentType int
  39. IsSsl bool
  40. }
  41. var (
  42. taskQueue = make(chan *HookTask, 1000)
  43. )
  44. // AddHookTask adds new hook task to task queue.
  45. func AddHookTask(t *HookTask) {
  46. taskQueue <- t
  47. }
  48. func init() {
  49. go handleQueue()
  50. }
  51. func handleQueue() {
  52. for {
  53. select {
  54. case t := <-taskQueue:
  55. // Only support JSON now.
  56. data, err := json.MarshalIndent(t.Payload, "", "\t")
  57. if err != nil {
  58. log.Error("hooks.handleQueue(json): %v", err)
  59. continue
  60. }
  61. _, err = httplib.Post(t.Url).SetTimeout(5*time.Second, 5*time.Second).
  62. Body(data).Response()
  63. if err != nil {
  64. log.Error("hooks.handleQueue: Fail to deliver hook: %v", err)
  65. continue
  66. }
  67. log.Info("Hook delivered: %s", string(data))
  68. }
  69. }
  70. }