Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I be using goroutines with http.ListenAndServe?

Tags:

go

goroutine

If I'm using http.ListenAndServe to provide responses when the user hits a URL, should I be firing off the corresponding actions in the function as a goroutine ?

For instance, say I'm listening at /:

func main() {
    http.HandleFunc("/", provideMainContent)
}

func provideMainContent(w http.ResponseWriter, r *http.Request) {
    /// Bunch of code, looks up details in databases, parses, then returns
}

Should the bunch of code in provideMainContent be wrapped in a goroutine so it doesn't slow down any potential requests that come after the fact ?

like image 596
Doug Smith Avatar asked Sep 14 '25 23:09

Doug Smith


1 Answers

Short answer, No

GoDoc from http.Serve :

Serve accepts incoming HTTP connections on the listener l, creating a new service goroutine for each. The service goroutines read requests and then call handler to reply to them.

However as mentioned in the question linked by @Mellow Marmot, there might be cases where you might want to spawn a goroutine to do some processing while you return from the handler so that the requester does not have to wait for all the processing to be done to get a response.

like image 181
John S Perayil Avatar answered Sep 17 '25 17:09

John S Perayil