Golang Context Cancelled on Goroutine

tech · Mar 22, 2021 · ~1 min

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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)
}

Thank you for reading!

· · ·

Love This Content?

Kindly support me via Bitcoin, Ko-fi, Trakteer, or just continue to read another content. Any kind of supports is greatly appreciated!