proxyAndRecord forwards the request, records the exchange, and writes the response back.
(ctx context.Context, w io.Writer, req *http.Request, scheme string)
| 144 | |
| 145 | // proxyAndRecord forwards the request, records the exchange, and writes the response back. |
| 146 | func (s *proxyServer) proxyAndRecord(ctx context.Context, w io.Writer, req *http.Request, scheme string) { |
| 147 | start := time.Now() |
| 148 | |
| 149 | // Capture request body. |
| 150 | var reqBody []byte |
| 151 | if req.Body != nil { |
| 152 | reqBody, _ = io.ReadAll(io.LimitReader(req.Body, maxBodySize+1)) |
| 153 | req.Body = io.NopCloser(strings.NewReader(string(reqBody))) |
| 154 | } |
| 155 | |
| 156 | // Remove hop-by-hop headers. |
| 157 | removeHopHeaders(req.Header) |
| 158 | |
| 159 | captured := &capturedRequest{ |
| 160 | Method: req.Method, |
| 161 | URI: req.URL.Path, |
| 162 | Host: req.URL.Host, |
| 163 | Scheme: scheme, |
| 164 | Headers: req.Header, |
| 165 | Query: req.URL.Query(), |
| 166 | Body: reqBody, |
| 167 | } |
| 168 | |
| 169 | // Forward the request to the real server. |
| 170 | transport := &http.Transport{ |
| 171 | TLSClientConfig: &tls.Config{}, |
| 172 | } |
| 173 | resp, err := transport.RoundTrip(req) |
| 174 | durationMs := float64(time.Since(start).Milliseconds()) |
| 175 | |
| 176 | if err != nil { |
| 177 | // Send 502 back to the client. |
| 178 | fmt.Fprintf(w, "HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\n\r\n") |
| 179 | s.storeEvent(ctx, captured, nil, durationMs, err.Error()) |
| 180 | return |
| 181 | } |
| 182 | defer resp.Body.Close() |
| 183 | |
| 184 | // Capture response body. |
| 185 | respBody, _ := io.ReadAll(io.LimitReader(resp.Body, maxBodySize+1)) |
| 186 | |
| 187 | capturedResp := &capturedResponse{ |
| 188 | StatusCode: resp.StatusCode, |
| 189 | Headers: resp.Header, |
| 190 | Body: respBody, |
| 191 | } |
| 192 | |
| 193 | // Write the response back to the client. |
| 194 | writeResponse(w, resp, respBody) |
| 195 | |
| 196 | s.storeEvent(ctx, captured, capturedResp, durationMs, "") |
| 197 | } |
| 198 | |
| 199 | func writeResponse(w io.Writer, resp *http.Response, body []byte) { |
| 200 | fmt.Fprintf(w, "HTTP/%d.%d %s\r\n", resp.ProtoMajor, resp.ProtoMinor, resp.Status) |
no test coverage detected