跳到主要内容

Go 快速开始

本文档介绍如何从零开始创建一个 Go 应用,并将其部署到 CloudBase HTTP 云函数中。

前置条件

在开始之前,请确保您已经:

  • 安装了 Go (推荐 Go 1.19 或更高版本)
  • 拥有腾讯云账号并开通了 CloudBase 服务
  • 了解基本的 Go 开发知识

第一步:创建项目目录

创建名为 helloworld-golang 的新目录,并进入该目录:

mkdir helloworld-golang
cd helloworld-golang

第二步:初始化项目配置

初始化 Go 模块:

go mod init helloworld-golang

这将在当前目录创建 go.mod 文件。

第三步:安装依赖

安装必要的依赖包:

go get github.com/gin-gonic/gin
go get github.com/gin-contrib/cors

这将安装 Gin Web 框架和 CORS 中间件。

第四步:编写应用代码

在同一目录中创建 main.go 文件,这是应用的入口文件:

⚠️ 重要提示:CloudBase HTTP 云函数的默认端口必须是 9000

package main

import (
"encoding/json"
"io"
"net/http"
"os"

"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)

// IPInfo 结构体用于存储 IP 信息
type IPInfo struct {
IP string `json:"ip"`
City string `json:"city"`
Region string `json:"region"`
Country string `json:"country"`
Loc string `json:"loc"`
Org string `json:"org"`
}

func main() {
r := gin.Default()

// 配置 CORS
r.Use(cors.New(cors.Config{
AllowOrigins: []string{"*"},
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"},
AllowHeaders: []string{"Origin", "Content-Length", "Content-Type", "Authorization"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: true,
}))

// 根路径
r.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "Hello World!")
})

// 获取 IP 信息
r.GET("/myip", func(c *gin.Context) {
resp, err := http.Get("https://ipinfo.io/json")
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Failed to fetch remote data",
"message": err.Error(),
})
return
}
defer resp.Body.Close()

body, err := io.ReadAll(resp.Body)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Failed to read response",
"message": err.Error(),
})
return
}

c.Data(http.StatusOK, "application/json", body)
})

// 健康检查
r.GET("/health", func(c *gin.Context) {
health := map[string]interface{}{
"status": "healthy",
"timestamp": "2024-01-01T00:00:00Z", // 实际应用中应使用 time.Now().Format(time.RFC3339)
"version": "1.0.0",
}
c.JSON(http.StatusOK, health)
})

// 404 处理
r.NoRoute(func(c *gin.Context) {
c.JSON(http.StatusNotFound, gin.H{"error": "Not Found"})
})

// 启动服务器
port := os.Getenv("PORT")
if port == "" {
port = "9000"
}

r.Run(":" + port)
}

此代码创建了一个基本的 Web 服务器,提供以下功能:

  • 根路径 (/):返回 "Hello World!" 消息
  • IP 查询 (/myip):获取并返回客户端 IP 信息
  • 健康检查 (/health):返回服务状态信息
  • 错误处理:对于未知路径返回 404 错误

第五步:创建启动脚本

💡 注意

  • 在 windows 下创建 scf_bootstrap 文件时,优先使用 nano scf_bootstrap 或者 vim scf_bootstrap 创建
  • 在 windows 下使用 vscode 创建 scf_bootstrap 文件时,部署到 HTTP 云函数可能会报错: scf_bootstrap 文件不存在
  • 这个错误是因为脚本文件包含了 Windows 格式的回车符(^M),导致 Linux 无法正确识别解释器路径。这是 WSL 中常见的问题

创建 scf_bootstrap 文件(无扩展名),这是 CloudBase 云函数的启动脚本:

#!/bin/bash
./main

⚠️ 注意

  • 文件名必须是 scf_bootstrap,没有扩展名
  • 确保文件具有执行权限

为启动脚本添加执行权限:

chmod +x scf_bootstrap

第六步:编译应用

编译 Go 应用:

GOOS=linux GOARCH=amd64 go build -o main main.go

这将在 Linux 环境下编译可执行文件,确保在 CloudBase 环境中正常运行。

第七步:本地测试(可选)

在部署之前,您可以在本地测试应用:

go run main.go

或者运行编译后的二进制文件:

./main

测试成功后,您可以通过以下方式验证:

  • 访问 http://localhost:9000/ 查看 Hello World 消息
  • 访问 http://localhost:9000/myip 查看 IP 信息
  • 访问 http://localhost:9000/health 查看健康状态

Ctrl + C 停止本地服务器。

第八步:部署到 CloudBase HTTP 云函数

准备部署文件

确保您的项目目录包含以下文件:

helloworld/
├── scf_bootstrap
├── go.mod
├── go.sum
├── main.go
└── main

通过控制台部署

  1. 登录 云开发平台/云函数
  2. 点击「新建云函数」
  3. 选择「HTTP 云函数」
  4. 填写函数名称(如:helloworld-go
  5. 选择运行时:Go 1.x
  6. 选择「本地上传」方式
  7. 将项目文件打包为 zip 文件并上传(请选择文件进行打包,不要打包根目录文件夹)
  8. 点击「确定」完成部署

通过 CLI 部署

详情请参考 CLI 部署 HTTP 函数

打包项目

如果需要手动打包,可以使用以下命令:

# 创建 zip 包
zip -r helloworld-golang.zip main scf_bootstrap

第九步:访问您的应用

部署成功后,您可以参考通过 HTTP 访问云函数设置自定义域名访问HTTP 云函数

您可以通过以下方式测试:

  • 访问根路径查看 Hello World 消息
  • 访问 /myip 路径查看 IP 信息
  • 访问 /health 路径查看服务状态

常见问题

Q: 为什么必须使用 9000 端口?

A: CloudBase HTTP 云函数要求应用监听 9000 端口,这是平台的标准配置。

Q: 如何查看函数日志?

A: 在 CloudBase 控制台的云函数页面,点击函数名称进入详情页,可以查看运行日志。

Q: 支持哪些 Go 版本?

A: CloudBase 支持 Go 1.16、1.17、1.18、1.19 等版本,建议使用较新的稳定版本。

Q: 如何处理 CORS 跨域问题?

A: 使用 Gin 的 CORS 中间件配置跨域,如示例代码所示。

Q: 函数冷启动时间较长怎么办?

A: 可以通过减小二进制文件大小、优化代码逻辑、使用静态编译等方式来减少冷启动时间。

Q: 如何进行交叉编译?

A: 使用 GOOS=linux GOARCH=amd64 环境变量进行 Linux 交叉编译,确保在 CloudBase 环境中正常运行。

Q: 为什么需要编译成二进制文件?

A: CloudBase 云函数环境是 Linux 系统,需要编译成对应平台的二进制文件才能正常运行。

最佳实践

  1. 错误处理:始终为 HTTP 请求添加适当的错误处理
  2. 响应头设置:正确设置 Content-Type 和其他必要的响应头
  3. 日志记录:使用 log 包记录关键信息,便于调试
  4. 环境变量:使用 os.Getenv() 管理配置信息
  5. 代码结构:对于复杂应用,建议按功能模块拆分文件
  6. 性能优化:使用连接池、缓存等技术提升性能
  7. 安全考虑:验证输入参数,防止注入攻击

下一步