-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsend.go
64 lines (56 loc) · 1.42 KB
/
send.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
package pact
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
// SendResponse is the response for a /send api call
type SendResponse struct {
RequestKeys []string `json:"requestKeys,omitempty"`
}
// Send sends a Pact command to a running Pact server and retrieves
// the transaction result
func Send(sendCmd []PrepareCommand, apiHost string) (res *SendResponse, err error) {
defer func() {
if e := recover(); e != nil {
switch er := e.(type) {
case Error:
err = er
case error:
err = er
}
}
}()
resp, err := sendRawCmds(sendCmd, apiHost)
EnforceNoError(err)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
EnforceNoError(err)
EnforceValid(resp.StatusCode == http.StatusOK, fmt.Errorf("%v", string(body)))
err = json.Unmarshal(body, &res)
EnforceNoError(err)
return
}
func sendRawCmds(sendCmds []PrepareCommand, apiHost string) (*http.Response, error) {
if apiHost == "" {
return nil, fmt.Errorf("apiHost shouldn't be empty")
}
cmds := []Command{}
for _, cmd := range sendCmds {
switch c := cmd.(type) {
case PrepareCont:
cmds = append(cmds, PrepareContCmd(c))
case PrepareExec:
cmds = append(cmds, PrepareExecCommand(c))
}
}
body, err := json.Marshal(SendCommand{
Cmds: cmds,
})
fmt.Println(string(body))
EnforceNoError(err)
bodyBytes := bytes.NewBuffer(body)
return http.Post(fmt.Sprintf("%s/api/v1/send", apiHost), "application/json", bodyBytes)
}