/
invoker.go
84 lines (72 loc) · 1.62 KB
/
invoker.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
/*
Copyright 2022 The CloudEvents Authors
SPDX-License-Identifier: Apache-2.0
*/
package invoker
import (
"errors"
"fmt"
"net/http/httputil"
"net/url"
"strings"
"time"
"github.com/cloudevents/conformance/pkg/event"
"github.com/cloudevents/conformance/pkg/http"
)
type Invoker struct {
URL *url.URL
Files []string
Delay *time.Duration
Recursive bool
Verbose bool
// PreHook allows for mutation of the outbound event before translation to
// a to HTTP request.
PreHook event.MutationFn
// PostHook allows for recording of the outbound HTTP request and resulting
// response and/or error.
PostHook http.ResultsFn
}
func (i *Invoker) Do() error {
events, err := event.FromYaml(strings.Join(i.Files, ","), i.Recursive)
if err != nil {
return err
}
var errs = make([]string, 0)
for _, e := range events {
if i.PreHook != nil {
e, err = i.PreHook(e)
if err != nil {
errs = append(errs, err.Error())
continue
}
}
req, err := http.EventToRequest(i.URL.String(), e)
if err != nil {
errs = append(errs, err.Error())
continue
}
if i.Verbose {
b, err := httputil.DumpRequestOut(req, true)
if err != nil {
fmt.Printf("Failed to dump request: %+v\n", err)
} else {
fmt.Println(string(b))
}
}
if i.URL.Host == "-" {
// Use "-" as a special hostname to indicate that actual requests should be skipped.
continue
}
if err := http.Do(req, i.PostHook); err != nil {
errs = append(errs, err.Error())
continue
}
if i.Delay != nil {
time.Sleep(*i.Delay)
}
}
if len(errs) > 0 {
return errors.New(strings.Join(errs, "\n"))
}
return nil
}