Merge branch 'feature/json_data'

- support md5 sum check
- support body length check
- support data post transmit
This commit is contained in:
Christoph Eck
2020-10-20 12:20:18 +02:00

43
http.go
View File

@@ -1,7 +1,9 @@
package cachet package cachet
import ( import (
"crypto/md5"
"crypto/tls" "crypto/tls"
"fmt"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"regexp" "regexp"
@@ -38,11 +40,27 @@ type HTTPMonitor struct {
// compiled to Regexp // compiled to Regexp
ExpectedBody string `mapstructure:"expected_body"` ExpectedBody string `mapstructure:"expected_body"`
bodyRegexp *regexp.Regexp bodyRegexp *regexp.Regexp
// content check
ExpectedMd5Sum string `mapstructure:"expected_md5sum"`
ExpectedLength int `mapstructure:"expected_length"`
// data
Data string `mapstructure:"data"`
} }
// TODO: test // TODO: test
func (monitor *HTTPMonitor) test() bool { func (monitor *HTTPMonitor) test() bool {
req, err := http.NewRequest(monitor.Method, monitor.Target, nil) var req *http.Request
var err error
if monitor.Data != "" {
dataBuffer := strings.NewReader(monitor.Data)
req, err = http.NewRequest(monitor.Method, monitor.Target, dataBuffer)
} else {
req, err = http.NewRequest(monitor.Method, monitor.Target, nil)
}
for k, v := range monitor.Headers { for k, v := range monitor.Headers {
req.Header.Add(k, v) req.Header.Add(k, v)
} }
@@ -67,14 +85,27 @@ func (monitor *HTTPMonitor) test() bool {
return false return false
} }
if monitor.bodyRegexp != nil { responseBody, err := ioutil.ReadAll(resp.Body)
// check response body responseLength := len(string(responseBody))
responseBody, err := ioutil.ReadAll(resp.Body) if err != nil {
if err != nil { monitor.lastFailReason = err.Error()
monitor.lastFailReason = err.Error() return false
}
if monitor.ExpectedLength > 0 && responseLength != monitor.ExpectedLength {
monitor.lastFailReason = "Expected response body length: " + strconv.Itoa(monitor.ExpectedLength) + ", got: " + strconv.Itoa(responseLength)
return false
}
if monitor.ExpectedMd5Sum != "" {
sum := fmt.Sprintf("%x", (md5.Sum(responseBody)))
if strings.Compare(sum, monitor.ExpectedMd5Sum) != 0 {
monitor.lastFailReason = "Expected respsone body MD5 checksum: " + monitor.ExpectedMd5Sum + ", got: " + sum
return false return false
} }
}
if monitor.bodyRegexp != nil {
if !monitor.bodyRegexp.Match(responseBody) { if !monitor.bodyRegexp.Match(responseBody) {
monitor.lastFailReason = "Unexpected body: " + string(responseBody) + ".\nExpected to match: " + monitor.ExpectedBody monitor.lastFailReason = "Unexpected body: " + string(responseBody) + ".\nExpected to match: " + monitor.ExpectedBody
return false return false