Repository navigation
Expand file tree
/
Copy pathresponse.go
More file actions
157 lines (143 loc) · 3.78 KB
/
Copy pathresponse.go
File metadata and controls
157 lines (143 loc) · 3.78 KB
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
package httpclient
import (
"bytes"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"net/url"
"strings"
"unicode/utf8"
"golang.org/x/text/encoding/charmap"
)
func (r *Request) Success() bool {
return r.StatusCode >= 200 && r.StatusCode < 300
}
// Error type given by [Receive] (or any dependent result method)
// in case of an un[Success]ful [Status] response.
type StatusError struct {
Code int
Status string
}
func (e *StatusError) Error() string {
return fmt.Sprintf("unsuccessful response code %s", e.Status)
}
func (r *Request) Receive() (err error) {
if r.Response == nil {
err = r.Send()
if err != nil {
return
}
if r.Response == nil {
panic("missing response")
}
}
if !r.Success() {
err = &StatusError{r.Response.StatusCode, r.Response.Status}
if r.Request != nil && r.Request.URL != nil {
err = &url.Error{r.Request.Method, r.Request.URL.String(), err}
}
}
return
}
func (r *Request) Bytes() (out []byte, err error) {
err = r.Receive()
if r.Response == nil {
return
}
defer r.Response.Body.Close()
out, ioerr := io.ReadAll(r.Response.Body)
if err == nil {
err = ioerr
}
return
}
// Error given by [Text] if the body does not seem to be proper Unicode.
// If a different encoding is expected, use [Bytes] instead to get raw data
// without this sanity check.
var ErrTextInvalid = fmt.Errorf("response body contains invalid UTF-8")
func (r *Request) Text() (string, error) {
body, err := r.Bytes()
if err == nil && !utf8.Valid(body) {
err = ErrTextInvalid
}
return string(body), err
}
// Specific error message given if [Json] encounters an xml body (for example
// an unexpected html error page), instead of a generic json.Unmarshal error:
// `invalid character '<' looking for beginning of value`
//
// In such cases, use [Preview] for further debugging:
//
// err := r.Json(&res)
// if err == httpclient.ErrJsonLikeXml {
// fmt.Printf("failed to get %s: %v (%s)", r.URL, err, r.Preview())
// }
var ErrJsonLikeXml = fmt.Errorf("initial '<' indicates xml not json")
// Error message if an empty response was received
// instead of expected [Json] or [Xml] data.
// Replaces more ambiguous unmarshalling exceptions
// "unexpected end of JSON input" or "EOF".
var ErrBodyEmpty = fmt.Errorf("empty body")
func (r *Request) Json(serial any) error {
body, err := r.Text()
if len(body) == 0 {
return ErrBodyEmpty
}
if body[0] == '<' {
buf := bytes.NewBufferString(body)
r.Response.Body = io.NopCloser(buf) // copy for rereading
return ErrJsonLikeXml
}
jserr := json.Unmarshal([]byte(body), serial)
if jserr != nil {
if err == nil {
err = jserr
} else {
err = errors.Join(err, jserr)
}
}
return err
}
func (r *Request) Xml(serial any) error {
if err := r.Receive(); err != nil {
return err
}
if r.Response.ContentLength == 0 {
return ErrBodyEmpty
}
d := xml.NewDecoder(r.Response.Body)
d.CharsetReader = func(xmlenc string, in io.Reader) (out io.Reader, err error) {
// support for some common non-utf8 encoding declarations
switch strings.ToLower(xmlenc) {
case "us-ascii":
out = in // subset of utf-8
case "iso-8859-1", "windows-1252":
out = charmap.Windows1252.NewDecoder().Reader(in)
default:
err = fmt.Errorf("unrecognised by httpclient.Xml")
}
return
}
return d.Decode(&serial)
}
// Abbreviate the first line of a response text,
// usually after failure to unmarshal [Json]
// to give an indication of any retrieved (error) message instead.
func (r *Request) Preview() (body string) {
body, _ = r.Text()
if body == "" {
return
}
cut := 160 // maximum length
if eol := strings.IndexByte(body, '\n'); eol > 0 && eol < cut {
// reduce length to first line ending
cut = eol + 3
}
if cut < len(body) {
// abbreviate exceeding line to truncated start and marker
body = body[:cut-3] + "..."
}
return
}