JeyJ
JeyJ

Reputation: 4070

Building Go module without main file

I have a small module that contains some shared code. The module looks like the following :

Shared
├── go.mod
├── go.sum
├── logging
│   └── logger.go
└── db-utils
    ├── db.go

If I'll try to build the Shared module from inside the directory I'm getting an error that no go file available under this module.

bash-3.2$ go build .
no Go files in /Users/xxxx/go/src/Shared

Is there a way to build a Go module that only has packages inside and doesn't have a main.go file? The motivation here is to use those packages in other go modules that can't access the internet or private repo in order to retrieve the packages.

Upvotes: 9

Views: 16536

Answers (3)

Toby Artisan
Toby Artisan

Reputation: 1809

If you only needed to build files in either the logging or db-utils directory, then you could executing the following from the root directory Shared:

go build <INSERT_MODULE_NAME_FROM_GO_MOD>/logging
go build <INSERT_MODULE_NAME_FROM_GO_MOD>/db-utils

I'm not certain if those commands will work if one of the files has a dependency on a file from the other directory.

Another command that will probably build the entire project is this:

go build ./...

Upvotes: 6

bcmills
bcmills

Reputation: 5187

The go command stores downloaded modules in the module cache as source code, not compiled object files. go build rebuilds the object files on demand and stores them in a separate build cache.

If you want to distribute a non-public module for use with other modules, you have a few options:

  1. You can publish the module to a private repository — typically accessed with credentials stored in a .netrc file — and use the GOPRIVATE environment variable to tell the go command not to try to fetch it from the public proxy and checksum servers.

  2. You can provide a private GOPROXY server or directory containing the source code, and use the GOPROXY environment variable to instruct the go command to use that proxy.

  3. You can publish the source code as a directory tree and use a replace directive in the consumer's go.mod file to slot it into the module graph.

Upvotes: 4

Zyl
Zyl

Reputation: 3270

Is there a way to build a go module that only has packages inside and doesn't have a main.go file?

No. The input for the build process is a package, not a module. Note how it says [packages] in the CLI documentation of go build.

When building a package leads to multiple packages being compiled, that is merely a consequence of direct and indirect import statements coming from .go-files located in the package you are building.

Note that Go does not support compiling packages to binaries to distribute closed-source libraries or such. This was not always the case, though. See #28152 and Binary-Only packages. The closest which exists to supporting that are plugins, but they are a work in progress and require resolution of symbols at runtime.

Upvotes: 2

Related Questions