开源项目教程:Google Cloud Functions with Go
google-cloud-functions-goGoogle Cloud Function tutorial and hacks to enable the use of Go.项目地址:https://gitcode.com/gh_mirrors/go/google-cloud-functions-go
1. 项目的目录结构及介绍
google-cloud-functions-go/
├── README.md
├── main.go
├── go.mod
├── go.sum
└── functions/
├── hello_http.go
└── hello_pubsub.go
- README.md: 项目说明文件,包含项目的基本信息和使用指南。
- main.go: 主程序文件,通常用于初始化项目和调用其他功能模块。
- go.mod: Go模块文件,定义了项目的依赖关系。
- go.sum: 依赖包的哈希值,确保依赖的完整性和安全性。
- functions/: 包含具体的函数实现文件。
- hello_http.go: 处理HTTP请求的函数。
- hello_pubsub.go: 处理Pub/Sub消息的函数。
2. 项目的启动文件介绍
main.go
package main
import (
"log"
"net/http"
"os"
"github.com/kelseyhightower/google-cloud-functions-go/functions"
)
func main() {
http.HandleFunc("/hello_http", functions.HelloHTTP)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
log.Printf("Listening on port %s", port)
if err := http.ListenAndServe(":"+port, nil); err != nil {
log.Fatal(err)
}
}
- main函数: 程序的入口点,设置HTTP路由并启动HTTP服务器。
- http.HandleFunc: 将
/hello_http
路径映射到functions.HelloHTTP
函数。 - os.Getenv("PORT"): 获取环境变量
PORT
,如果没有设置则默认使用8080
端口。
3. 项目的配置文件介绍
go.mod
module github.com/kelseyhightower/google-cloud-functions-go
go 1.15
require (
cloud.google.com/go v0.75.0
google.golang.org/genproto v0.0.0-20210122163508-8081c04a3579
google.golang.org/grpc v1.35.0
)
- module: 定义模块路径。
- go: 指定Go版本。
- require: 列出项目依赖的包及其版本。
go.sum
cloud.google.com/go v0.75.0 h1:xP6mFZf4GZsZLs/EV9IeSjCgUSzPu5eBQ+J1Vg/f+YA=
cloud.google.com/go v0.75.0/go.mod h1:gx9jr41Es0dWwAPC35s9JH5JFvL4cRRGuMyQlV0sdw8=
google.golang.org/genproto v0.0.0-20210122163508-8081c04a3579 h1:39mN9Ul4J1A4BdzrLc5s55JbLPqRmWb6AaTZkaXZFk2A=
google.golang.org/genproto v0.0.0-20210122163508-8081c04a3579/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
google.golang.org/grpc v1.35.0 h1:LTp+GxiHgtNmK0v5+Bn42dINq4VbJX0lSOWOh3+T03k=
google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6
google-cloud-functions-goGoogle Cloud Function tutorial and hacks to enable the use of Go.项目地址:https://gitcode.com/gh_mirrors/go/google-cloud-functions-go