고루틴에서 취소된 Golang 컨텍스트

Golang의 요청 컨텍스트는 goroutine에 전달될 때 자동으로 수행되고 부모 goroutine은 이미 완료되었습니다.

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)
}

좋은 웹페이지 즐겨찾기