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 ( 
  "flag" 
  "fmt" 
  "os" 
) 
var fatalErr error 
func fatal(e error) { 
  fmt.Println(e) 
  flag.PrintDefaults() 
  fatalErr = e 
} 
func main() { 
  defer func() { 
    if fatalErr != nil { 
      os.Exit(1) 
    } 
  }() 
} 

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

Get Go: Design Patterns for Real-World Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.