Standard library / net/http

http.NewRequestWithContext()

Construct an outgoing request whose context controls its lifetime. Expected stdout: 'true\n'.

Formal Syntax & Structure

go syntaxgo
func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error)

Parameters & Attributes

NameTypeDescription
ctxcontext.ContextContext controlling cancellation.
methodstringHTTP method token.
urlstringDestination URL string.
bodyio.ReaderOptional reader containing the request body.

Return Value

(*Request, error)

Operation result; check errors and validity indicators when returned.

Working Example

Example Snippetgo
package main
import (  "context"  "fmt"  "net/http")
func main() {  ctx, cancel := context.WithCancel(context.Background())  defer cancel()  r := must(http.NewRequestWithContext(ctx, "GET", "https://example.invalid", nil))  cancel()  fmt.Println(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