Organizing Your Code

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Chapter 2 Interacting with Your Users | TOC | Defining the To-Do API 👉

Before you start developing command-line tools, let’s talk a little about how to organize your code. Go is a relatively new programming language, so the community is still discussing different approaches for structuring Go programs. This section presents a common approach for developing command-line tools.

As you learned in Building the Basic Word Counter, Go programs are composed of packages, which consist of one or more Go source code files that can be combined into executable programs or libraries. To create an executable program, you define a package named main which contains a function named main that serves as the entry point for your executable program.

For this tool you’ll use another common Go pattern to create a separate package containing the business logic, which in this case is the logic for working with to-do items. The command-line interface that works with this business logic is defined in a subdirectory named cmd.

By using this pattern, you separate the business logic from the command-line implementation and enable other developers to reuse the to-do code in their own programs.

This is the desired directory structure for this tool:

​ todo
​ ├── cmd
​ │ └── todo
​ │ ├── main.go
​ │ └── main_test.go…

--

--

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.