-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrequest_factory.go
More file actions
200 lines (166 loc) · 4.84 KB
/
request_factory.go
File metadata and controls
200 lines (166 loc) · 4.84 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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
package draft
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
)
// RequestFactory -
type RequestFactory func(RequestFactoryParams, RequestPrepare) (*http.Request, error)
// RequestPrepare -
type RequestPrepare func(req *http.Request) error
// RequestFactoryParams -
type RequestFactoryParams struct {
Project string `json:"project"`
Access AccessType `json:"access"`
AccessExtra string `json:"access_extra"`
Method MethodType `json:"method"`
Scheme string `json:"scheme"`
Host string `json:"host"`
Path string `json:"path"`
Values url.Values `json:"values"`
}
const (
HeaderRequestID = "X-Request-Id"
)
// DefaultRequestFactory -
func DefaultRequestFactory(params RequestFactoryParams, prepare RequestPrepare) (*http.Request, error) {
req, err := NewHTTPRequest(params)
if err != nil {
return nil, err
}
req.URL.RawQuery = params.Values.Encode()
if prepare != nil {
err = prepare(req)
if err != nil {
return nil, err
}
}
return req, nil
}
// NewHTTPRequest -
func NewHTTPRequest(params RequestFactoryParams) (*http.Request, error) {
req := &http.Request{
Method: string(params.Method),
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
}
req.Header = make(http.Header)
req.Header.Set(HeaderRequestID, NewRequestID())
scheme := params.Scheme
if scheme == "" {
scheme = "https"
}
rawURL := scheme + "://" + params.Host + params.Path
u, err := url.Parse(rawURL)
if err != nil {
return nil, fmt.Errorf("url '%s' parse failed: %s", rawURL, err)
}
req.URL = u
req.Host = u.Host
return req, nil
}
// GetRequestPrepare -
func GetRequestPrepare(params RequestFactoryParams) RequestPrepare {
for _, access := range pureDocConfig.Rights {
if access.ID == params.Access {
for _, extra := range access.Extra {
if extra.Name == params.AccessExtra && extra.ReqPrepare != nil {
return extra.ReqPrepare
}
}
return access.ReqPrepare
}
}
return nil
}
// NewRequestID -
func NewRequestID() string {
id := make([]byte, 5)
rand.Read(id)
return hex.EncodeToString(id)
}
type requestFactoryResponse struct {
General requestFactoryResponseGeneral `json:"general"`
ResponseHeaders http.Header `json:"response_headers"`
RequestHeaders http.Header `json:"request_headers"`
QueryParams url.Values `json:"query_params"`
ResponseBody interface{} `json:"response_body"`
}
type requestFactoryResponseGeneral struct {
RequestURL string `json:"request_url"`
RequestMethod string `json:"request_method"`
StatusCode int `json:"status_code"`
StatusText string `json:"status_text"`
// RemoteAddress string `json:"remote_address"`
}
func doDraftRequest(api *APIService, w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
params := RequestFactoryParams{}
err := json.Unmarshal([]byte(r.URL.Query().Get("data")), ¶ms)
if err != nil {
writeRequestFactoryError(w, "PARSE_JSON_REQUEST_DATA", err)
return
}
requestFactory := DefaultRequestFactory
if pureDocConfig.RequestFactory != nil {
requestFactory = pureDocConfig.RequestFactory
}
req, err := requestFactory(params, GetRequestPrepare(params))
if err != nil {
writeRequestFactoryError(w, "CREATE_REQUEST", err)
return
}
result := requestFactoryResponse{
General: requestFactoryResponseGeneral{req.URL.String(), req.Method, 0, ""},
RequestHeaders: req.Header,
QueryParams: req.URL.Query(),
}
reqResp, err := api.endpointClient.Do(req)
if err != nil {
writeRequestFactoryError(w, "DO_REQUEST", err)
return
}
result.General.StatusCode = reqResp.StatusCode
result.General.StatusText = reqResp.Status
result.ResponseHeaders = reqResp.Header
defer reqResp.Body.Close()
body, err := ioutil.ReadAll(reqResp.Body)
if err != nil {
result.ResponseBody = requestFactoryError{"READ_RESPONSE_BODY", err.Error()}
} else if strings.Contains(reqResp.Header.Get("Content-Type"), "application/json") {
r := make(map[string]interface{})
err := json.Unmarshal(body, &r)
if err != nil {
result.ResponseBody = requestFactoryError{
"PARSE_JSON_RESPONSE_BODY",
fmt.Sprintf("parse %q failed: %s", string(body), err),
}
} else {
result.ResponseBody = r
}
} else {
result.ResponseBody = string(body)
}
jsonResult, err := json.Marshal(result)
if err != nil {
writeRequestFactoryError(w, "RESPONSE_MARSHAL", err)
return
}
w.Write(jsonResult)
}
type requestFactoryError struct {
Type string `json:"type"`
Error string `json:"error"`
}
func writeRequestFactoryError(w http.ResponseWriter, t string, err error) {
log.Printf("[godraft:request] [warn] type: %q, message: %s", t, err)
json, _ := json.Marshal(requestFactoryError{t, err.Error()})
w.Write(json)
}