'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.



Solution 1:[1]

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.

Solution 2:[2]

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 ./...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Zyl
Solution 2