Logo

dev-resources.site

for different kinds of informations.

Golang Context Cancelled On Goroutine

Published at
3/26/2021
Categories
notes
go
context
goroutine
Author
clavinjune
Categories
4 categories in total
notes
open
go
open
context
open
goroutine
open
Author
10 person written this
clavinjune
open
Golang Context Cancelled On Goroutine

Golang’s request context is automatically be done when passed on goroutine, and its parents goroutine is already done.

package main

import (
    "context"
    "log"
    "net/http"
    "time"
)

func foo(ctx context.Context) {
    ctx, cancel := context.WithTimeout(ctx, 60*time.Second)
    defer cancel()

    req, _ := http.NewRequestWithContext(ctx,
        http.MethodGet, "https://google.com", nil)

    _, err := http.DefaultClient.Do(req)

    log.Println(err) // Get "https://google.com": context canceled
}

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        go foo(r.Context())
    }) // context will be done when it reaches here

    http.ListenAndServe(":8888", nil)
}

Enter fullscreen mode Exit fullscreen mode

Featured ones: