Search⌘ K
AI Features

Handling Output from External Programs

Explore how to execute external programs in Go and handle their output and errors efficiently. Understand capturing STDOUT and STDERR to detect issues when exit codes are unreliable. Learn to implement custom execution steps and interfaces to process outputs in CI pipelines, enabling you to validate code formatting and enhance command-line application robustness.

Overview

The two external programs we’ve executed are well-behaved; if something goes wrong, they return an error that we can capture and use to make decisions. Unfortunately, not all programs work like that.

In some cases, the program exits with a successful return code even when something goes wrong. In these cases a message in STDOUT or STDERR generally provides details about the error condition. In other cases, a program completes successfully as designed but something on its output tells us that the condition represents an error.

When executing external programs in Go, we can handle both of these scenarios by capturing the program’s output and parsing it to make decisions.

The next step in the pipeline is the execution of the gofmt tool to validate whether the target project conforms to the Go code formatting standards or not. The gofmt tool doesn’t return an error. Its default behavior is to print the properly formatted version of the Go program to STDOUT. Typically, users run gofmt with the -w option to overwrite the original file with the correctly formatted version. But in this case, we only want to verify the program and validate the formatting as part of the CI pipeline. We can use the -l option which returns the name of the file if the file doesn’t match the correct formatting. We can find more information about the gofmt tool in the official documentation.

Next pipeline step

In our next pipeline step, we’ll execute gofmt -l, examine its output, and verify if it’s different than an empty string, in which case ...