I'd like to use a helper package from Go Cloud Function. The package has some helper logic that can be shared between multiple functions. But, what is the right way to structure the packages so they all work? The package should be in the same project - not published and public as a completely separate package.
I work at Google. The goal for this question is to proactively answer common questions and help developers starting off with Go on GCF.
You can use subpackages with Go modules. Go modules are Go's new dependency management solution - they let you work outside of
GOPATH
and let you manage the exact versions of each dependency you have.Modules also let you define a group of Go packages with the same import path prefix. When you're writing a function, this lets you import other packages in your module.
The function you're deploying needs to be at the root of your module.
Here is an example file structure and how packages would be imported:
This setup has your function in
function.go
and tested byfunction_test.go
. They are in a module namedexample.com/foo
.helperpackage
can be imported byfunction.go
usingexample.com/foo/helperpackage
.This also has a
cmd
directory, which may be helpful for local testing. You can importexample.com/foo
and start an HTTP server which registers your function as an HTTP handler. For example:Note: You could use a vendor directory to achieve the same result. But, all of the packages your function imports would need to be in the vendor directory (with the full import path), which works, but is cumbersome to maintain. It's uncommon to copy sub-packages into your vendor directory, so I wouldn't recommend this.