-
Notifications
You must be signed in to change notification settings - Fork 8
/
http_response.go
137 lines (130 loc) · 3.44 KB
/
http_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
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
package httputilmore
import (
"errors"
"fmt"
"io"
"net/http"
"time"
"github.com/grokify/mogo/encoding/jsonutil"
"github.com/grokify/mogo/errors/errorsutil"
)
// ProxyResponse copies the information from a `*http.Response` to a
// `http.ResponseWriter`.
func ProxyResponse(w http.ResponseWriter, resp *http.Response) ([]byte, error) {
if resp == nil {
return nil, errors.New("E_NIL_HTTP_RESPONSE")
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
_, err = w.Write(body)
if err != nil {
return body, err
}
headers := []string{
HeaderContentEncoding,
HeaderContentLanguage,
HeaderContentTransferEncoding,
HeaderContentType}
for _, header := range headers {
if len(resp.Header.Get(header)) > 0 {
w.Header().Add(header, resp.Header.Get(header))
}
}
w.WriteHeader(resp.StatusCode)
return body, nil
}
func CondenseResponseNot2xxToError(resp *http.Response, err error, msg string) error {
if err != nil {
if len(msg) > 0 {
return errorsutil.Wrap(err, msg)
} else {
return err
}
} else if resp == nil {
return errors.New("*http.Response_is_nil")
} else if resp.StatusCode < 200 || resp.StatusCode > 299 {
if len(msg) > 0 {
msg += ": "
}
more := []string{}
body, err := io.ReadAll(resp.Body)
if err != nil {
more = append(more, err.Error())
} else {
more = append(more, string(body))
}
moreString := ""
jsn, err := json.Marshal(more)
if err != nil {
moreString = err.Error()
} else {
moreString = string(jsn)
}
return fmt.Errorf("non_2xx_status_code [%d] [%s] [%s]", resp.StatusCode, msg, moreString)
}
return nil
}
// ResponseInfo is a generic struct to handle response info.
type ResponseInfo struct {
Name string `json:"name,omitempty"` // to distinguish from other requests
Method string `json:"method,omitempty"`
URL string `json:"url,omitempty"`
StatusCode int `json:"statusCode,omitempty"`
Time time.Time `json:"time,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
Body string `json:"body,omitempty"`
}
// ToJSON returns ResponseInfo as a JSON byte array, embedding json.Marshal
// errors if encountered.
func (resIn *ResponseInfo) ToJSON() []byte {
bytes, err := json.Marshal(resIn)
if err != nil {
resIn2 := ResponseInfo{StatusCode: 500, Body: err.Error()}
bytes, _ := json.Marshal(resIn2)
return bytes
}
return bytes
}
func ResponseWriterWriteJSON(w http.ResponseWriter, statusCode int, body any, prefix, indent string) error {
if w == nil {
return errors.New("nil response writer")
}
wroteStatus := false
var errs []error
if body != nil {
bytes, err := jsonutil.MarshalSimple(body, "", " ")
if err != nil {
errs = append(errs, err)
gr := ResponseInfo{
Body: err.Error()}
bytes, err = jsonutil.MarshalSimple(gr, "", " ")
if err != nil {
errs = append(errs, err)
}
w.WriteHeader(500)
_, err2 := w.Write(bytes)
errs = append(errs, err2)
return errorsutil.Join(false, errs...)
}
_, err = w.Write(bytes)
if err != nil {
errs = append(errs, err)
gr := ResponseInfo{
Body: err.Error()}
bytes, err = jsonutil.MarshalSimple(gr, "", " ")
if err != nil {
errs = append(errs, err)
}
w.WriteHeader(500)
_, err2 := w.Write(bytes)
errs = append(errs, err2)
return errorsutil.Join(false, errs...)
}
}
if !wroteStatus && statusCode != 0 {
w.WriteHeader(statusCode)
}
return nil
}