How can I use a sub-packages with Go on Google Clo

2019-07-06 01:52发布

问题:

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.

回答1:

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:

.
├── cmd
│   └── main.go # Useful for testing. Can import and setup your function.
├── function.go # Can import example.com/foo/helperpackage
├── function_test.go
├── go.mod # module example.com/foo
└── helperpackage
    └── helper.go

This setup has your function in function.go and tested by function_test.go. They are in a module named example.com/foo. helperpackage can be imported by function.go using example.com/foo/helperpackage.

This also has a cmd directory, which may be helpful for local testing. You can import example.com/foo and start an HTTP server which registers your function as an HTTP handler. For example:

package main

import (
    "log"
    "net/http"

    "example.com/foo"
)

func main() {
    http.Handle("/HelloHTTP", foo.HelloHTTP)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

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.