Search code examples
gogolandgo-build

How to embed Go Sdk binaries inside of Go Binary


I actually have a simple goal.

I want to quickly install go in environments without internet access. I want to create a go project in which I add the tar file with the go sdk. When I build my code, I want to extract the tar first and then ınstall the resulting go sdk. But for this, I think I need to add the .tar.gz file into the go binary file.

I am beginner in Go. Does anyone have any idea how I can do it or can I do something like this?


Thank you for your advice. I know these things.

You just have to say this.

Is it possible to add a tar.gz file inside the binary file I got with go build command?

When the application is running, it will find the my-tar.tar.gz file in itself, extract it from the tar and process it. So instead of using both a binary and a tar file, I will just use one binary.


Solution

  • Yes, it is possible to do what you want. No, I would not take this approach for a lot of reasons - but - here is how at a high level:

    Use Go's embed.FS capability to get the tarball into your executable.

    Note: You will need a different tarball for each architecture, and hence a different build of your executable for every platform. That could be accomplished with build tags.


    Next, you have to extract the tarball after you copy it onto the actual file system. The easiest way would be to just use the os/exec package and do an exec.Command to run tar to extract it.

    If tar is not on your target machine - then you could use these packages:

    “archive/tar”
    “compress/gzip"
    

    And follow an approach discussed here (a bit dated but generally should still work)

    Another interesting thread - do it without having to inflate to the filesystem first:

    https://github.com/golang/go/issues/61232

    https://pkg.go.dev/github.com/nlepage/go-tarfs