-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
110 lines (93 loc) · 2.41 KB
/
request.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
package hyper
import (
"bytes"
"context"
"errors"
"io"
"net/http"
"github.com/infiniteloopcloud/log"
)
func checkBaseURL(baseURL string) error {
if baseURL == "" {
return errors.New("base url is empty, set it with SetBaseURL(...)")
}
return nil
}
func endpoint(baseURL, s string) string {
return baseURL + s
}
type RequestOpts struct {
BaseURL string
Method string
Endpoint string
Request interface{}
Headers map[string]string
ContextKeys map[string]log.ContextField
SkipBodyClose bool
Client *http.Client
}
//nolint:gocritic
func Request(ctx context.Context, respStruct interface{}, opts RequestOpts) (*http.Response, error) {
if err := checkBaseURL(opts.BaseURL); err != nil {
return nil, err
}
var r *http.Request
var err error
if req, ok := opts.Request.(io.Reader); ok {
r, err = http.NewRequest(opts.Method, endpoint(opts.BaseURL, opts.Endpoint), req)
} else if opts.Request != nil {
b := new(bytes.Buffer)
if err := jsonEncoder.Encode(b, opts.Request); err != nil {
return nil, err
}
r, err = http.NewRequest(opts.Method, endpoint(opts.BaseURL, opts.Endpoint), b)
} else {
r, err = http.NewRequest(opts.Method, endpoint(opts.BaseURL, opts.Endpoint), nil)
}
if err != nil {
return nil, err
}
r.Header = IntoHeader(ctx, r.Header, opts.ContextKeys)
if opts.Headers != nil {
for k, v := range opts.Headers {
r.Header.Add(k, v)
}
}
resp, err := opts.Client.Do(r)
if err != nil {
return nil, err
}
if !opts.SkipBodyClose {
defer resp.Body.Close()
}
if respStruct != nil {
if err := jsonEncoder.Decode(resp.Body, respStruct); err != nil {
return nil, err
}
}
return resp, nil
}
func SilentProxy(ctx context.Context, w http.ResponseWriter, resp *http.Response) {
for key, valueSlice := range resp.Header {
for _, v := range valueSlice {
w.Header().Add(key, v)
}
}
if w.Header().Get("Content-Type") == "" {
w.Header().Set("Content-Type", "application/json")
}
w.WriteHeader(resp.StatusCode)
if resp.Body == nil {
defer resp.Body.Close()
return
}
var b bytes.Buffer
if _, err := io.Copy(&b, resp.Body); err != nil {
log.Error(ctx, err, "error copying resp to buffer")
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
if _, err := w.Write(b.Bytes()); err != nil {
log.Error(ctx, err, "error copying resp to buffer")
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
}