How to statically link a Go binary that uses crypto / tls?

If you try to compile the following Go program:

package main import _ "crypto/tls" func main() { } 

You will end up with a dynamically linked Go bean. This annoys me (I am building the Go binary inside a Docker container that uses a different libc from my host, which will cause the binary to not run on my host).

How does one power go to creating such a program statically?

+6
source share
1 answer

The only OS where crypto/tls uses cgo is darwin, where it needs to call FetchPEMRoots to get the root CAs.

The reason your program uses cgo is because crypto/tls imports the net package, which by default refers to the host resolver. You can create a net package without using cgo using the netgo build tag.

 go build -tags netgo 

Or, if you are in a release where std lib packages will not be created by default, you can run them for compilation using the new installsuffix

 go build -installsuffix netgo -tags netgo 

Since you will not have the need or ability to use cgo in your environment, you can simply create everything with CGO_ENABLED=0 to completely disable cgo.

+8
source

All Articles