Home > Article > Backend Development > Will a Goroutine Launched in an HTTP Handler Always Finish After the Response is Sent?
Question:
In the provided example code, where a goroutine is initiated within an HTTP handler (HomeHandler), will the goroutine always complete execution, even after the server returns the response to the client?
Example 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) }
Answer:
Yes, the goroutine started in worker will complete its execution in all situations.
Goroutines are lightweight threads within a Go program and are not constrained by the execution of the main function or the HTTP handler. They continue to run concurrently unless they encounter errors or are explicitly terminated. In this case, the worker goroutine is started asynchronously, and the HomeHandler function returns immediately after writing the response to the client. Even after the handler function returns and the server sends the response, the worker goroutine continues to execute until it finishes its task of sleeping for 10 seconds and printing its completion message.
The only scenarios where a goroutine may not complete are:
The above is the detailed content of Will a Goroutine Launched in an HTTP Handler Always Finish After the Response is Sent?. For more information, please follow other related articles on the PHP Chinese website!