Executing External Programs

Powerful Command-Line Applications in Go — by Ricardo Gerardi (60 / 127)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Chapter 6 Controlling Processes | TOC | Handling Errors 👉

In this initial version of the goci tool, you’ll define the main structure of your program and then execute the first step of the CI pipeline: building the program. Start by creating a directory called processes/goci for this tool under your book project’s root directory:

​ ​$ ​​mkdir​​ ​​-p​​ ​​$HOME/pragprog.com/rggo/processes/goci​
​ ​$ ​​cd​​ ​​$HOME/pragprog.com/rggo/processes/goci​

Initialize a new Go module for this project called goci:

​ ​$ ​​go​​ ​​mod​​ ​​init​​ ​​pragprog.com/rggo/processes/goci​
​ go: creating new go.mod: module pragprog.com/rggo/processes/goci

For this tool, you’ll use the run function pattern that you saw in Creating a Basic Markdown Preview Tool. The run function contains the main logic of the program, while the function main contains only the code that parses the command-line flags and calls the run function. This approach allows the execution of integration tests by executing the run function during tests.

Create the file main.go in the goci directory and open it in your editor. Define the package name and add the import section. Import the flag package to parse command-line options, the fmt package to handle output, the io package that provides the io.Writer interface, the os package to interact…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.