Go 快速开始
本 文档介绍如何从零开始创建一个 Go 应用,并将其部署到 CloudBase HTTP 云函数中。
前置条件
在开始之前,请确保您已经:
- 安装了 Go (推荐 Go 1.19 或更高版本)
- 拥有腾讯云账号并创建了云开发环境
- 了解基本的 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 环境中正常运行。