@@ -7,10 +7,15 @@ package gogs
7
7
import (
8
8
"bytes"
9
9
"encoding/json"
10
+ "errors"
10
11
"fmt"
11
12
"net/http"
12
13
)
13
14
15
+ var (
16
+ ErrInvalidReceiveHook = errors .New ("Invalid JSON payload received over webhook" )
17
+ )
18
+
14
19
type Hook struct {
15
20
Id int64 `json:"id"`
16
21
Type string `json:"type"`
@@ -55,3 +60,58 @@ func (c *Client) EditRepoHook(user, repo string, id int64, opt EditHookOption) e
55
60
http.Header {"content-type" : []string {"application/json" }}, bytes .NewReader (body ))
56
61
return err
57
62
}
63
+
64
+ type PayloadAuthor struct {
65
+ Name string `json:"name"`
66
+ Email string `json:"email"`
67
+ UserName string `json:"username"`
68
+ }
69
+
70
+ type PayloadCommit struct {
71
+ Id string `json:"id"`
72
+ Message string `json:"message"`
73
+ Url string `json:"url"`
74
+ Author * PayloadAuthor `json:"author"`
75
+ }
76
+
77
+ type PayloadRepo struct {
78
+ Id int64 `json:"id"`
79
+ Name string `json:"name"`
80
+ Url string `json:"url"`
81
+ Description string `json:"description"`
82
+ Website string `json:"website"`
83
+ Watchers int `json:"watchers"`
84
+ Owner * PayloadAuthor `json:"owner"`
85
+ Private bool `json:"private"`
86
+ }
87
+
88
+ // Payload represents a payload information of hook.
89
+ type Payload struct {
90
+ Secret string `json:"secret"`
91
+ Ref string `json:"ref"`
92
+ Commits []* PayloadCommit `json:"commits"`
93
+ Repo * PayloadRepo `json:"repository"`
94
+ Pusher * PayloadAuthor `json:"pusher"`
95
+ Before string `json:"before"`
96
+ After string `json:"after"`
97
+ CompareUrl string `json:"compare_url"`
98
+ }
99
+
100
+ // ParseHook parses Gogs webhook content.
101
+ func ParseHook (raw []byte ) (* Payload , error ) {
102
+ hook := new (Payload )
103
+ if err := json .Unmarshal (raw , hook ); err != nil {
104
+ return nil , err
105
+ }
106
+ // it is possible the JSON was parsed, however,
107
+ // was not from Github (maybe was from Bitbucket)
108
+ // So we'll check to be sure certain key fields
109
+ // were populated
110
+ switch {
111
+ case hook .Repo == nil :
112
+ return nil , ErrInvalidReceiveHook
113
+ case len (hook .Ref ) == 0 :
114
+ return nil , ErrInvalidReceiveHook
115
+ }
116
+ return hook , nil
117
+ }
0 commit comments