-
Notifications
You must be signed in to change notification settings - Fork 0
/
hook_client.go
95 lines (78 loc) · 1.98 KB
/
hook_client.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
93
94
95
// Copyright 2018 The Harbor Authors. All rights reserved.
package opm
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
"github.com/vmware/harbor/src/jobservice/models"
"github.com/vmware/harbor/src/jobservice/utils"
)
const (
clientTimeout = 10 * time.Second
maxIdleConnections = 20
idleConnectionTimeout = 30 * time.Second
)
//DefaultHookClient is for default use.
var DefaultHookClient = NewHookClient()
//HookClient is used to post the related data to the interested parties.
type HookClient struct {
client *http.Client
}
//NewHookClient return the ptr of the new HookClient
func NewHookClient() *HookClient {
client := &http.Client{
Timeout: clientTimeout,
Transport: &http.Transport{
MaxIdleConns: maxIdleConnections,
IdleConnTimeout: idleConnectionTimeout,
},
}
return &HookClient{
client: client,
}
}
//ReportStatus reports the status change info to the subscribed party.
//The status includes 'checkin' info with format 'check_in:<message>'
func (hc *HookClient) ReportStatus(hookURL string, status models.JobStatusChange) error {
if utils.IsEmptyStr(hookURL) {
return errors.New("empty hook url") //do nothing
}
//Parse and validate URL
url, err := url.Parse(hookURL)
if err != nil {
return err
}
//Marshal data
data, err := json.Marshal(&status)
if err != nil {
return err
}
//New post request
req, err := http.NewRequest(http.MethodPost, url.String(), strings.NewReader(string(data)))
if err != nil {
return err
}
res, err := hc.client.Do(req)
if err != nil {
return err
}
defer res.Body.Close() //close connection for reuse
//Should be 200
if res.StatusCode != http.StatusOK {
if res.ContentLength > 0 {
//read error content and return
dt, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}
return errors.New(string(dt))
}
return fmt.Errorf("failed to report status change via hook, expect '200' but got '%d'", res.StatusCode)
}
return nil
}