/
response.go
62 lines (51 loc) · 1.47 KB
/
response.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
// Copyright 2014 ALTOROS
// Licensed under the AGPLv3, see LICENSE file for details.
package https
import (
"fmt"
"net/http"
"strings"
)
// Response represents HTTPS client response
type Response struct {
*http.Response
}
// VerifyJSON checks the response has specified code and carries application/json body
func (r Response) VerifyJSON(code int) error {
return r.Verify(code, "application/json")
}
// Verify checks the response has specified code and body with specified content type
func (r Response) Verify(code int, contentType string) error {
if err := r.VerifyCode(code); err != nil {
return err
}
if err := r.VerifyContentType(contentType); err != nil {
return err
}
return nil
}
// VerifyCode checks the response has specified code
func (r Response) VerifyCode(code int) error {
if r.StatusCode != code {
return fmt.Errorf("expected HTTP code: %d, got code: %d, %s", code, r.StatusCode, r.Status)
}
return nil
}
// VerifyContentType checks the response has specified content type
func (r Response) VerifyContentType(contentType string) error {
if contentType == "" {
return nil
}
contentType = strings.ToLower(contentType)
vv, ok := r.Header["Content-Type"]
if !ok {
return fmt.Errorf("header Content-Type not found in response, expected \"%s\"", contentType)
}
for _, v := range vv {
v = strings.ToLower(v)
if strings.Contains(v, contentType) {
return nil
}
}
return fmt.Errorf("expected Content-Type: \"%s\", received \"%v\"", contentType, vv)
}