...
1
2
3
4
5
6
7
8
9
10
11
12
13 package chttp
14
15 import (
16 "encoding/json"
17 "fmt"
18 "mime"
19 "net/http"
20 )
21
22
23 type HTTPError struct {
24
25
26
27 Response *http.Response `json:"-"`
28
29
30 Reason string `json:"reason"`
31 }
32
33 func (e *HTTPError) Error() string {
34 if e.Reason == "" {
35 return http.StatusText(e.HTTPStatus())
36 }
37 if statusText := http.StatusText(e.HTTPStatus()); statusText != "" {
38 return fmt.Sprintf("%s: %s", statusText, e.Reason)
39 }
40 return e.Reason
41 }
42
43
44 func (e *HTTPError) HTTPStatus() int {
45 return e.Response.StatusCode
46 }
47
48
49
50 func ResponseError(resp *http.Response) error {
51 if resp.StatusCode < 400 {
52 return nil
53 }
54 if resp.Body != nil {
55 defer CloseBody(resp.Body)
56 }
57 httpErr := &HTTPError{
58 Response: resp,
59 }
60 if resp != nil && resp.Request != nil && resp.Request.Method != "HEAD" && resp.ContentLength != 0 {
61 if ct, _, _ := mime.ParseMediaType(resp.Header.Get("Content-Type")); ct == typeJSON {
62 _ = json.NewDecoder(resp.Body).Decode(httpErr)
63 }
64 }
65 return httpErr
66 }
67
View as plain text