/
esapi.response.go
92 lines (79 loc) · 1.97 KB
/
esapi.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
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
// Licensed to Elasticsearch B.V. under one or more agreements.
// Elasticsearch B.V. licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
package esapi
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"strconv"
"strings"
)
// Response represents the API response.
//
type Response struct {
StatusCode int
Header http.Header
Body io.ReadCloser
}
// String returns the response as a string.
//
// The intended usage is for testing or debugging only.
//
func (r *Response) String() string {
var (
out = new(bytes.Buffer)
b1 = bytes.NewBuffer([]byte{})
b2 = bytes.NewBuffer([]byte{})
tr io.Reader
)
if r != nil && r.Body != nil {
tr = io.TeeReader(r.Body, b1)
defer r.Body.Close()
if _, err := io.Copy(b2, tr); err != nil {
out.WriteString(fmt.Sprintf("<error reading response body: %v>", err))
return out.String()
}
defer func() { r.Body = ioutil.NopCloser(b1) }()
}
if r != nil {
out.WriteString(fmt.Sprintf("[%d %s]", r.StatusCode, http.StatusText(r.StatusCode)))
if r.StatusCode > 0 {
out.WriteRune(' ')
}
} else {
out.WriteString("[0 <nil>]")
}
if r != nil && r.Body != nil {
out.ReadFrom(b2) // errcheck exclude (*bytes.Buffer).ReadFrom
}
return out.String()
}
// Status returns the response status as a string.
//
func (r *Response) Status() string {
var b strings.Builder
if r != nil {
b.WriteString(strconv.Itoa(r.StatusCode))
b.WriteString(" ")
b.WriteString(http.StatusText(r.StatusCode))
}
return b.String()
}
// IsError returns true when the response status indicates failure.
//
func (r *Response) IsError() bool {
return r.StatusCode > 299
}
// Warnings returns the deprecation warnings from response headers.
//
func (r *Response) Warnings() []string {
return r.Header["Warning"]
}
// HasWarnings returns true when the response headers contain deprecation warnings.
//
func (r *Response) HasWarnings() bool {
return len(r.Warnings()) > 0
}