So how do the 2016 US Presidential Candidates fare on Twitter? Let’s find out with Go!
Here’s how to build your very own dashboard that queries Twitter and finds out how many Twitter followers each candidate has. You can see the live dashboard here, below is a static screenshot:
You need to have a verified Twitter account, and know a bit of Go. Let’s start!
Go to https://apps.twitter.com/ and create a new Twitter app. Generate an access token from the “Keys and Access Tokens” tab. We’ll need the Consumer Key, Consumer Secret, Access Token and Access Token Secret values.
Now let’s get the code from github to hack on:
Let’s edit the code and put in the keys that we got from Twitter earlier, then build and run:
If there were any errors while querying Twitter, it’ll be printed and the fun stops. Otherwise head over to http://localhost:8080/ and see who’s leading!
BTW, note that
go build puts the binary in the current directory, while
go get puts it in
We’re using this nice library to query Twitter. We initialize it this way:
And having done that, call the users.lookup Twitter API with the list of known Twitter handles of the presidential candidates.
This returns, among other things, the count of followers for each Twitter account. We store this in a slice, and sort it by follower count:
We want to keep fetching this information and updating it every minute in one (the main) goroutine, while other goroutines access this information to render HTML pages. The information therefore, is stored mutex-protected. The TwitterInfo slice created above is stored after locking a mutex, as in the code below. Note that we don’t copy the slice objects, the slice itself is stored and retrieved.
We want to show the time of fetch in HTML page, so we remember that during
.In(TZ_ET) converts the current time into Eastern (Daylight)
TZ_ET is a
*time.Location that we loaded using:
We keep updating the information each minute, with a simple loop in the main goroutine:
Next up is the web server itself, which actually has fewer lines than the list of candidates:
This loads a single template (defined as a multi-line string in file
creates a handler to serve all URLs and starts a web server. (Actually, that
is quite awesome.)
The handler gets the information we fetched above and renders the template with it:
That’s it! Poke around the code for more goodies that are not currently used, like the number of tweets and profile image URL for each candidate.
Here are some useful links: