DEV Community

Clavin June
Clavin June

Posted on • Originally published at clavinjune.dev on

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay