如何在Go on Google Cloud Functions中使用子包? [英] How can I use a sub-packages with Go on Google Cloud Functions?

查看:86
本文介绍了如何在Go on Google Cloud Functions中使用子包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Go Cloud Function的帮助程序包.该软件包具有一些可以在多个功能之间共享的帮助程序逻辑.但是,什么是构造软件包以便它们都能正常工作的正确方法呢?该程序包应该在同一个项目中-不应作为完全独立的程序包发布和公开.

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.

我在Google工作.该问题的目的是主动回答常见问题,并帮助开发人员从使用Go on GCF开始.

推荐答案

您可以将子包与转到模块. Go模块是Go的新依赖项管理解决方案-它们使您可以在GOPATH之外工作,并可以管理每个依赖项的确切版本.

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.

模块还使您可以定义一组具有相同导入路径前缀的Go软件包.在编写函数时,这使您可以在模块中导入其他软件包.

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

此设置在function.go中具有您的功能,并已通过function_test.go进行了测试.它们位于名为example.com/foo的模块中. helperpackage可以由function.go使用example.com/foo/helperpackage导入.

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.

这也有一个cmd目录,这可能对本地测试很有帮助.您可以导入example.com/foo并启动一个HTTP服务器,该服务器将您的功能注册为HTTP处理程序.例如:

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.

这篇关于如何在Go on Google Cloud Functions中使用子包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆