dousu8456 2019-01-18 13:56
浏览 50
已采纳

如何在Go on Google Cloud Functions中使用子包?

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条回答 默认 最新

  • dongtangyi8962 2019-01-18 13:56
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?