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
| Name | Type | Description |
|---|---|---|
| ctx | context.Context | Context controlling cancellation. |
| method | string | HTTP method token. |
| url | string | Destination URL string. |
| body | io.Reader | Optional 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) }}