Goroutine execution inside http handler
If I run goroutine inside an http handler, will it terminate even after returning a response? Here's some sample code:
package main
import (
"fmt"
"net/http"
"time"
)
func worker() {
fmt.Println("worker started")
time.Sleep(time.Second * 10)
fmt.Println("worker completed")
}
func HomeHandler(w http.ResponseWriter, r *http.Request) {
go worker()
w.Write([]byte("Hello, World!"))
}
func main() {
http.HandleFunc("/home", HomeHandler)
http.ListenAndServe(":8081", nil)
}
In the above example, what worker
goroutine will terminate in all situations? Or is there any special case where it will not be completed?
+3
source to share
2 answers
Yes, it will end, nothing will stop there.
The only thing that stops the execution of goroutines "outside" is returned from the function main()
(which also means that your program ends, but in your case it never happens). And other circumstances that lead to unstable conditions such as out of memory.
+6
source to share