1 Star 0 Fork 0

zhangjungang/beats

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
check.go 1.94 KB
一键复制 编辑 原始数据 按行查看 历史
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
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/zhangjungang/beats.git
git@gitee.com:zhangjungang/beats.git
zhangjungang
beats
beats
v5.3.2

搜索帮助