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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more