Understanding goroutines for web API

Just start with Go and hope to build a simple web API. I am considering using Gorilla Garbage ( http://www.gorillatoolkit.org/pkg/mux ) to handle web requests.

I'm not sure how to best use Go's concurrency options to handle requests. I read somewhere that the function main

is actually a goroutine or should I send every request to the goroutine as it gets? I apologize if I'm leaving.

+3


source to share


2 answers


Assuming you are using Go http.ListenAndServe

to serve your HTTP requests, the documentation clearly states that each incoming connection is handled by a separate goroutine for you. http://golang.org/pkg/net/http/#Server.Serve Usually you call ListenAndServe

from within your function main

.

Garbage Gorilla is just a package for more flexible routing of requests to your handlers than http.DefaultServeMux

. It doesn't actually handle the incoming connection or request, it just passes it to your handler.



I highly recommend that you read some documentation, in particular this tutorial https://golang.org/doc/articles/wiki/#tmp_3 when writing web applications.

+7


source


I give the answer, although I voted to be too broad.

Anyway, none of this is required. You already think about it. If you haven't read this, it looks like a decent tutorial; http://thenewstack.io/make-a-restful-json-api-go/



You can just set up your routes as with most standard rest frameworks and let the webserver / framework worry about concurrency at the request processing level. You should use goroutines to generate a response to a request, say if you need to aggregate data from 10 files in a folder. A thoughtful example, but this is where you would allocate 1 goroutine per file, summarize all information, read the pipe in a non-blocking selection, and then return the result. You can expect all entry points to your code to be called in an asynchronous, non-blocking way, if that makes sense ...

+1


source







All Articles