Standard library / net/http/httptest
httptest.NewRequestWithContext()
Creates a synthetic incoming server request with the supplied context; introduced in Go 1.23. Expected stdout: 'true\n'.
Formal Syntax & Structure
go syntaxgo
func NewRequestWithContext(ctx context.Context, method, target string, body io.Reader) *http.RequestParameters & Attributes
| Name | Type | Description |
|---|---|---|
| ctx | context.Context | Context controlling cancellation. |
| method | string | HTTP method token. |
| target | string | Target error to match. |
| body | io.Reader | Optional reader containing the request body. |
Return Value
*http.Request
Operation result; check errors and validity indicators when returned.
Working Example
Example Snippetgo
package main
import ( "context" "errors" "fmt" "net/http/httptest")
func main() { ctx, cancel := context.WithCancel(context.Background()) r := httptest.NewRequestWithContext(ctx, "GET", "/", nil) cancel() fmt.Println(errors.Is(r.Context().Err(), context.Canceled))}
func must[T any](v T, e error) T { if e != nil { panic(e) } return v}func check(e error) { if e != nil { panic(e) }}