Home >Backend Development >Golang >Will My Goroutine Finish After the HTTP Response is Sent?
When executing a goroutine within an HTTP handler, it's natural to wonder whether its execution will continue after the response has been returned. Consider the following 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) }
This code spins up a goroutine within the HomeHandler that sleeps for 10 seconds before printing completion. Once the response is written, the main goroutine returns from the HomeHandler function.
In this specific scenario, the goroutine will indeed complete its execution, printing the statements "worker started" and "worker completed" to the console. This is because:
The only way to prematurely terminate the goroutine in this case would be to encounter an unstable state, such as running out of memory, or to explicitly stop the goroutine using synchronization techniques (not covered in this code example).
The above is the detailed content of Will My Goroutine Finish After the HTTP Response is Sent?. For more information, please follow other related articles on the PHP Chinese website!