Rewriting the main() function for better testing
There exists a clever way that you can rewrite each main() function in order to make testing (and benchmarking) a lot easier. The main() function has a restriction, which is that you cannot call it from test code—this technique presents a solution to that problem using the code found in main.go. The import block is omitted to save space.
func main() {
err := run(os.Args, os.Stdout)
if err != nil {
fmt.Printf("%s\n", err)
return
}
}
As we cannot have an executable program without a main() function, we have to create a minimalistic one. What main() does is call run(), which is our own customized version of main(), send the desired os.Args to it, and collect the return value of run():
func run(args []string, stdout io.Writer) error {
if len(args) == 1 {
return errors.New("No input!")
}
// Continue with the implementation of run()
// as you would...