-2

Why does my Go HTTP server freeze when I call another API inside a goroutine?

func handler(w http.ResponseWriter, r *http.Request) {
    go func() {
        resp, err := http.Get("https://example.com/data")
        if err != nil {
            log.Println("request failed:", err)
            return
        }
        defer resp.Body.Close()
        body, _ := io.ReadAll(resp.Body)
        log.Println("result:", string(body))
    }()

    w.Write([]byte("OK"))
}
New contributor
ezequiel is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
2
  • Not sure there is enough code to reproduce this. How are you calling this? What do you mean by freeze? How are seeing that behavior? You should not need to wrap an http handler in a go routine like this. If you actually have more logic in your handler then you need to wait for that routine to finish. It’s likely you’re writing OK and that routine is not finished. So that outbound call begins and is lost. Commented 5 hours ago
  • By “freeze” I mean the server stops responding after a few requests. The handler isn’t called anymore and the goroutine never finishes. I used the goroutine to avoid blocking the client, but I’ll try handling the call synchronously instead. Commented 4 hours ago

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.