-
Notifications
You must be signed in to change notification settings - Fork 0
/
webhook.go
92 lines (83 loc) · 2.38 KB
/
webhook.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package github
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"github.com/google/go-github/github"
"github.com/sirupsen/logrus"
"io/ioutil"
"net/http"
"regexp"
"strconv"
)
//create webhook,return id of webhook
func (c *client) createGithubWebhook(user string, repo string, accesstoken string, webhookURL string, secret string, events []string) (string, error) {
data := user + ":" + accesstoken
sEnc := base64.StdEncoding.EncodeToString([]byte(data))
name := "web"
active := true
hook := github.Hook{
Name: &name,
Active: &active,
Config: make(map[string]interface{}),
Events: events,
}
hook.Config["url"] = webhookURL
hook.Config["content_type"] = "json"
hook.Config["secret"] = secret
hook.Config["insecure_ssl"] = "1"
logrus.Debugf("hook to create:%v", hook)
b := new(bytes.Buffer)
json.NewEncoder(b).Encode(hook)
client := http.Client{}
APIURL := fmt.Sprintf("%s/repos/%s/%s/hooks", c.API, user, repo)
req, err := http.NewRequest("POST", APIURL, b)
req.Header.Add("Authorization", "Basic "+sEnc)
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
respData, err := ioutil.ReadAll(resp.Body)
logrus.Infof("respData:%v", string(respData))
if resp.StatusCode > 399 {
return "", errors.New(string(respData))
}
err = json.Unmarshal(respData, &hook)
if err != nil {
return "", err
}
return strconv.Itoa(hook.GetID()), err
}
func getUserRepoFromURL(repoURL string) (string, string, error) {
reg := regexp.MustCompile(".*/([^/]*?)/([^/]*?).git")
match := reg.FindStringSubmatch(repoURL)
if len(match) != 3 {
return "", "", fmt.Errorf("error getting user/repo from gitrepoUrl:%v", repoURL)
}
return match[1], match[2], nil
}
func (c *client) deleteGithubWebhook(user string, repo string, accesstoken string, id string) error {
data := user + ":" + accesstoken
sEnc := base64.StdEncoding.EncodeToString([]byte(data))
client := http.Client{}
APIURL := fmt.Sprintf("%s/repos/%s/%s/hooks/%v", c.API, user, repo, id)
req, err := http.NewRequest("DELETE", APIURL, nil)
if err != nil {
return err
}
req.Header.Add("Authorization", "Basic "+sEnc)
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
respData, err := ioutil.ReadAll(resp.Body)
if resp.StatusCode > 399 {
return errors.New(string(respData))
}
logrus.Debugf("after delete,%v,%v", string(respData))
return err
}