Including OS-Specific Files in the Build

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Including OS-Specific Data | TOC | Testing the Notify Package 👉

Using runtime.GOOS to verify the current operating system is a practical way to include OS-specific parameters and data in your application. But it’s not a good approach to include larger pieces of code because doing so may lead to convoluted code and it may not be possible in some cases to redefine the code within the condition block.

In these cases, you can use build constraints,[78] also known as build tags, which are a mechanism that lets you include and exclude files from your build and your tests according to different criteria.

In their most basic form, you can use build tags to tag Go source files and include them in your build when you provide the respective tag as a value to the parameter -tags=TAG when building or testing your code. You already used this concept in Executing Integration Tests, to include integration test files when required.

Go also allows you to provide tags based on the operating system and architecture. For example, if you add the build constraint // +build linux, Go automatically includes this file in the build when targeting the Linux operating system.

Instead of providing the build tag, you can include the target operating system or architecture as a suffix in the file name, in front of the…

--

--

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.