Counting votes

The second program we are going to implement is the counter tool, which will be responsible for watching out for votes in NSQ, counting them, and keeping MongoDB up to date with the latest numbers.

Create a new folder called counter alongside twittervotes, and add the following code to a new main.go file:

package main
import (
var fatalErr error
func fatal(e error) {
  fatalErr = e
func main() {
  defer func() {
    if fatalErr != nil {

Normally when we encounter an error in our code, we use a call like log.Fatal or os.Exit, which immediately terminates the program. Exiting the program with a non-zero exit code is important, because it is our way of telling the operating ...

Get Go: Building Web Applications now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.