Standard library / net/http
http.Request.WithContext()
Return a shallow request copy with the supplied non-nil context; header map remains shared. Expected stdout: 'a\n'.
Formal Syntax & Structure
go syntaxgo
func (r *Request) WithContext(ctx context.Context) *RequestParameters & Attributes
| Name | Type | Description |
|---|---|---|
| ctx | context.Context | Context controlling cancellation. |
Return Value
*Request
Operation result; check errors and validity indicators when returned.
Working Example
Example Snippetgo
package main
import ( "context" "fmt" "net/http")
func main() { r := must(http.NewRequest("GET", "https://example.invalid/", nil)) ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := r.WithContext(ctx) c.Header.Set("X-Demo", "a") fmt.Println(r.Header.Get("X-Demo"))}
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) }}