forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
check.go
101 lines (85 loc) · 1.94 KB
/
check.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
96
97
98
99
100
101
package http
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
)
type RespCheck func(*http.Response) error
var (
errBodyMismatch = errors.New("body mismatch")
)
func makeValidateResponse(config *responseParameters) RespCheck {
var checks []RespCheck
if config.Status > 0 {
checks = append(checks, checkStatus(config.Status))
} else {
checks = append(checks, checkStatusOK)
}
if len(config.RecvHeaders) > 0 {
checks = append(checks, checkHeaders(config.RecvHeaders))
}
if len(config.RecvBody) > 0 {
checks = append(checks, checkBody([]byte(config.RecvBody)))
}
return checkAll(checks...)
}
func checkOK(_ *http.Response) error { return nil }
// TODO: collect all errors into on error message.
func checkAll(checks ...RespCheck) RespCheck {
switch len(checks) {
case 0:
return checkOK
case 1:
return checks[0]
}
return func(r *http.Response) error {
for _, check := range checks {
if err := check(r); err != nil {
return err
}
}
return nil
}
}
func checkStatus(status uint16) RespCheck {
return func(r *http.Response) error {
if r.StatusCode == int(status) {
return nil
}
return fmt.Errorf("received status code %v expecting %v", r.StatusCode, status)
}
}
func checkStatusOK(r *http.Response) error {
if r.StatusCode >= 400 {
return errors.New(r.Status)
}
return nil
}
func checkHeaders(headers map[string]string) RespCheck {
return func(r *http.Response) error {
for k, v := range headers {
value := r.Header.Get(k)
if v != value {
return fmt.Errorf("header %v is '%v' expecting '%v' ", k, value, v)
}
}
return nil
}
}
func checkBody(body []byte) RespCheck {
return func(r *http.Response) error {
// read up to len(body)+1 bytes for comparing content to be equal
in := io.LimitReader(r.Body, int64(len(body))+1)
content, err := ioutil.ReadAll(in)
if err != nil {
return err
}
if !bytes.Equal(body, content) {
return errBodyMismatch
}
return nil
}
}