@@ -7,10 +7,15 @@ package gogs
77import (
88 "bytes"
99 "encoding/json"
10+ "errors"
1011 "fmt"
1112 "net/http"
1213)
1314
15+ var (
16+ ErrInvalidReceiveHook = errors .New ("Invalid JSON payload received over webhook" )
17+ )
18+
1419type Hook struct {
1520 Id int64 `json:"id"`
1621 Type string `json:"type"`
@@ -55,3 +60,58 @@ func (c *Client) EditRepoHook(user, repo string, id int64, opt EditHookOption) e
5560 http.Header {"content-type" : []string {"application/json" }}, bytes .NewReader (body ))
5661 return err
5762}
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