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.Request

Parameters & Attributes

NameTypeDescription
ctxcontext.ContextContext controlling cancellation.
methodstringHTTP method token.
targetstringTarget error to match.
bodyio.ReaderOptional 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)  }}
Go Reference