Test is used for internal debugging by passing a *http.Request. Config is optional and defaults to a 1s error on timeout, 0 timeout will disable it completely.
(req *http.Request, config ...TestConfig)
| 1353 | // Config is optional and defaults to a 1s error on timeout, |
| 1354 | // 0 timeout will disable it completely. |
| 1355 | func (app *App) Test(req *http.Request, config ...TestConfig) (*http.Response, error) { |
| 1356 | // Default config |
| 1357 | cfg := TestConfig{ |
| 1358 | Timeout: time.Second, |
| 1359 | FailOnTimeout: true, |
| 1360 | } |
| 1361 | |
| 1362 | // Override config if provided |
| 1363 | if len(config) > 0 { |
| 1364 | cfg = config[0] |
| 1365 | } |
| 1366 | |
| 1367 | // Add Content-Length if not provided with body |
| 1368 | if req.Body != http.NoBody && req.Header.Get(HeaderContentLength) == "" { |
| 1369 | req.Header.Add(HeaderContentLength, strconv.FormatInt(req.ContentLength, 10)) |
| 1370 | } |
| 1371 | |
| 1372 | // Ensure Host header is present in the dump (required by fasthttp) |
| 1373 | if req.Host == "" { |
| 1374 | if req.URL != nil && req.URL.Host != "" { |
| 1375 | req.Host = req.URL.Host |
| 1376 | } else { |
| 1377 | req.Host = "localhost" |
| 1378 | } |
| 1379 | } |
| 1380 | |
| 1381 | // Clear RequestURI so DumpRequest writes origin-form request line with |
| 1382 | // Host header instead of absolute-form URI without Host header. |
| 1383 | req.RequestURI = "" |
| 1384 | |
| 1385 | // Dump raw http request |
| 1386 | dump, err := httputil.DumpRequest(req, true) |
| 1387 | if err != nil { |
| 1388 | return nil, fmt.Errorf("failed to dump request: %w", err) |
| 1389 | } |
| 1390 | |
| 1391 | // Create test connection |
| 1392 | conn := new(testConn) |
| 1393 | |
| 1394 | // Write raw http request |
| 1395 | if _, err = conn.r.Write(dump); err != nil { |
| 1396 | return nil, fmt.Errorf("failed to write: %w", err) |
| 1397 | } |
| 1398 | // prepare the server for the start |
| 1399 | app.startupProcess() |
| 1400 | |
| 1401 | // Serve conn to server |
| 1402 | channel := make(chan error, 1) |
| 1403 | go func() { |
| 1404 | var returned bool |
| 1405 | defer func() { |
| 1406 | if !returned { |
| 1407 | channel <- ErrHandlerExited |
| 1408 | } |
| 1409 | }() |
| 1410 | |
| 1411 | channel <- app.server.ServeConn(conn) |
| 1412 | returned = true |