generated from knative-extensions/sample-source
-
Notifications
You must be signed in to change notification settings - Fork 3
/
callback.go
79 lines (66 loc) · 1.7 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
72
73
74
75
76
77
78
79
package resources
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"github.com/hashicorp/go-retryablehttp"
)
// parse errors
var (
ErrInvalidHTTPMethod = errors.New("invalid HTTP Method")
ErrParsingPayload = errors.New("error parsing payload")
)
type CallbackPayload struct {
State Status `json:"state"`
Description string `json:"description"`
Context string `json:"context"`
TargetURL string `json:"target_url"`
}
type Status string
const (
StatusSuccess Status = "success"
StatusFailure Status = "failure"
StatusError Status = "error"
)
// EmitValidationCallback send callback to given callbackURL
func (callback *CallbackPayload) EmitValidationCallback(callbackURL string) error {
if callbackURL == "" {
return fmt.Errorf("callbackURL is not set")
}
payload, err := json.Marshal(callback)
if err != nil {
return err
}
resp, err := retryablehttp.Post(callbackURL, "application/json", bytes.NewBuffer(payload))
if err != nil {
return err
}
if c := resp.StatusCode; c < http.StatusOK || http.StatusBadRequest <= c {
return fmt.Errorf("failed to send callback. status code: %d", c)
}
return nil
}
// Parse verifies and parses the events specified and returns the payload object or an error
func Parse(r *http.Request) (interface{}, error) {
defer func() {
_, _ = io.Copy(ioutil.Discard, r.Body)
_ = r.Body.Close()
}()
if r.Method != http.MethodPost {
return nil, ErrInvalidHTTPMethod
}
payload, err := ioutil.ReadAll(r.Body)
if err != nil || len(payload) == 0 {
return nil, ErrParsingPayload
}
var pl CallbackPayload
err = json.Unmarshal([]byte(payload), &pl)
if err != nil {
return nil, ErrParsingPayload
}
return pl, err
}