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 operating system that something went wrong, and we didn't complete our task successfully. The problem with the normal approach is that any deferred functions we have scheduled (and therefore any teardown...