Benjamin Pollack
Benjamin Pollack

Reputation: 28460

How can I handle platform-specific modules in Go?

I'm writing a command-line utility in Go that (as part of its operation) needs to get a password from the user. There's a great gopass module for Unix that does this, and I know how to write one for the Windows console. The problem is that the Windows module obviously won't build on *nix, and the *nix version won't build on Windows. Since Go lacks any preprocessor support (as far as I can tell), I have absolutely no idea what the right way to approach this is. I know it's possible, since Go itself must do this for its own libraries, but the tooling I'm used to (conditional imports/preprocessors/etc.) seems to be missing.

Upvotes: 4

Views: 703

Answers (1)

Dominik Honnef
Dominik Honnef

Reputation: 18440

Go has build constraints, which can either be specified as comments in a .go file, or as part of the file name.

One set of constraints is for target operating system, so you can have one file for Windows, one for e.g. Linux and implement the same function in two different ways in the two.

More information on build constraints are at http://golang.org/pkg/go/build/#hdr-Build_Constraints

Upvotes: 8

Related Questions