forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
callback.go
71 lines (62 loc) · 1.82 KB
/
callback.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
package util
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
// CallbackInvoker posts results to a callback URL when a STI build is done.
type CallbackInvoker interface {
ExecuteCallback(callbackURL string, success bool, messages []string) []string
}
// NewCallbackInvoker creates an instance of the default CallbackInvoker implementation
func NewCallbackInvoker() CallbackInvoker {
invoker := &callbackInvoker{}
invoker.postFunc = invoker.httpPost
return invoker
}
type callbackInvoker struct {
postFunc func(url, contentType string, body io.Reader) (resp *http.Response, err error)
}
// ExecuteCallback prepares a JSON payload and posts it to the specified callback URL
func (c *callbackInvoker) ExecuteCallback(callbackURL string, success bool, messages []string) []string {
buf := new(bytes.Buffer)
writer := bufio.NewWriter(buf)
for _, message := range messages {
fmt.Fprintln(writer, message)
}
writer.Flush()
d := map[string]interface{}{
"payload": buf.String(),
"success": success,
}
jsonBuffer := new(bytes.Buffer)
writer = bufio.NewWriter(jsonBuffer)
jsonWriter := json.NewEncoder(writer)
jsonWriter.Encode(d)
writer.Flush()
var (
resp *http.Response
err error
)
for retries := 0; retries < 3; retries++ {
resp, err = c.postFunc(callbackURL, "application/json", jsonBuffer)
if err != nil {
errorMessage := fmt.Sprintf("Unable to invoke callback: %v", err)
messages = append(messages, errorMessage)
}
if resp != nil {
if resp.StatusCode >= 300 {
errorMessage := fmt.Sprintf("Callback returned with error code: %d", resp.StatusCode)
messages = append(messages, errorMessage)
}
break
}
}
return messages
}
func (*callbackInvoker) httpPost(url, contentType string, body io.Reader) (resp *http.Response, err error) {
return http.Post(url, contentType, body)
}