Golang Building Multi Platform Issue
I'm building a go application that I want to build for both Linux and Windows. For the Windows piece, I would like it to have the ability to install as a Windows Service. So in my app, I've included the following packages:
golang.org/x/sys/windows/svc
golang.org/x/sys/windows/svc/debug
golang.org/x/sys/windows/svc/eventlog
golang.org/x/sys/windows/svc/mgr
It builds fine for Windows and the service installs with no issues. But when I try to build it for linux:
GOOS=linux GOARCH=amd64 go build -o app-amd64-linux
package github.com/user/app
imports golang.org/x/sys/windows/svc: build constraints exclude all Go files in
C:\Users\User\go\pkg\mod\golang.org\x\sys@v0.0.0-20220728004956-3c1f35247d10\windows\svc\package github.com/user/app
imports golang.org/x/sys/windows/svc/debug: build constraints exclude all Go files in
C:\Users\User\go\pkg\mod\golang.org\x\sys@v0.0.0-20220728004956-3c1f35247d10\windows\svc\debug\package github.com/user/app
imports golang.org/x/sys/windows/svc/eventlog: build constraints exclude all Go files in
C:\Users\User\go\pkg\mod\golang.org\x\sys@v0.0.0-20220728004956-3c1f35247d10\windows\svc\eventlog\package github.com/user/app
imports golang.org/x/sys/windows/svc/mgr: build constraints exclude all Go files in
C:\Users\User\go\pkg\mod\golang.org\x\sys@v0.0.0-20enter code here220728004956-3c1f35247d10\windows\svc\mgr
In the code, I'm checking and only using these packages if the app is running as a windows service. Is there a way ignore these errors? Or only import them when building for Windows? Or maybe something I can change in go.mod to only require those for windows?
As a workaround you might use Build Constrants:
https://pkg.go.dev/go/build#hdr-Build_Constraints
Tim Cooper made in this post an elaborate answer how to implement those:
main.go
package main
func main() {
println("main()")
conditionalFunction()
}
a.go
// +build COMPILE_OPTION
package main
func conditionalFunction() {
println("conditionalFunction")
}
b.go
// +build !COMPILE_OPTION
package main
func conditionalFunction() {
}
Output:
*% go build -o example ; ./example
main()
% go build -o example -tags COMPILE_OPTION ; ./example
main()
conditionalFunction*
I copied the answer one-to-one in order not to lose it. Somebody might correct me if this ain't wished.