Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding goroutines for web API

Tags:

go

Just starting out with Go and hoping to create a simple Web API. I'm looking into using Gorilla mux (http://www.gorillatoolkit.org/pkg/mux) to handle web requests.

I'm not sure how to best use Go's concurrency options to handle the requests. Did I read somewhere that the main function is actually a goroutine or should I dispatch each request to a goroutine as they are received? Apologies if I'm "way off".

like image 662
tommyd456 Avatar asked May 06 '15 16:05

tommyd456


People also ask

What are Goroutines and how do they work?

A goroutine is a lightweight execution thread in the Go programming language and a function that executes concurrently with the rest of the program. Goroutines are incredibly cheap when compared to traditional threads as the overhead of creating a goroutine is very low.

What do you use Goroutines for?

A coroutine is a concurrency design pattern that you can use on Android to simplify code that executes asynchronously. Coroutines were added to Kotlin in version 1.3 and are based on established concepts from other languages.

How do you communicate between two Goroutines?

Go provides a way for bidirectional communication between two goroutines through channels. Bidirectional communication means either party can send or receive a message, so Go provides channels as the mechanism to send or receive data between goroutines. With limitchannel <- i , the value of i enters the channel. fmt.

Are Goroutines the same as threads?

Threads are hardware dependent. Goroutines have easy communication medium known as channel. Thread does not have easy communication medium. Due to the presence of channel one goroutine can communicate with other goroutine with low latency.


1 Answers

Assuming you're using the Go's 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 You would usually call ListenAndServe from your main function.

Gorilla mux is simply a package for more flexible routing of requests to your handlers than the http.DefaultServeMux. It doesn't actually handle the incoming connection or request just simply relays it to your handler.

I highly suggest you read a bit of the documentation, specifically this guide https://golang.org/doc/articles/wiki/#tmp_3 on writing web applications.

like image 89
Leo Correa Avatar answered Sep 23 '22 02:09

Leo Correa