Skip to main content

Go Quick Start

This document describes how to create a Go application from scratch and deploy it to CloudBase HTTP cloud functions.

Prerequisites

Before you begin, ensure that you have:

  • Installed Go (recommended Go 1.19 or later version)
  • Have a Tencent Cloud account with CloudBase service activated
  • Have a basic understanding of Go development

Step 1: Create a Project Directory

Create a new directory named helloworld-golang and go to the directory:

mkdir helloworld-golang
cd helloworld-golang

Step 2: Initialize Project Configuration

Initialize the Go module:

go mod init helloworld-golang

This will create a go.mod file in the current directory.

Step 3: Install Dependencies

Install the necessary dependency packages:

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

This will install the Gin Web framework and CORS middleware.

Step 4: Write Application Code

Create a main.go file in the same directory, which serves as the entry point file for the application:

⚠️ Important Note: The default port for CloudBase HTTP cloud function must be 9000.

package main

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

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

// The IPInfo struct is used to store IP information
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()

// Configure 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,
}))

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

// Obtain IP information
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)
})

// Health Check
r.GET("/health", func(c *gin.Context) {
health := map[string]interface{}{
"status": "healthy",
"timestamp": "2024-01-01T00:00:00Z", // In actual applications, use time.Now().Format(time.RFC3339)
"version": "1.0.0",
}
c.JSON(http.StatusOK, health)
})

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

// Start the server
port := os.Getenv("PORT")
if port == "" {
port = "9000"
}

r.Run(":" + port)
}

This code creates a basic Web server that provides the following features:

  • Root path (/): Returns a "Hello World!" message
  • IP Query (/myip): Obtain and return the client IP information.
  • Health Check (/health): Returns the service status information.
  • Error Handling: Returns a 404 error for unknown paths

Step 5: Create a Startup Script

Create the scf_bootstrap file (without an extension), which is the startup script for CloudBase cloud functions:

#!/bin/bash
./main

⚠️ Note:

  • The file name must be scf_bootstrap without an extension
  • Ensure the file has execute permission

Grant execute permission to the startup script:

chmod +x scf_bootstrap

Step 6: Compile the Application

Compile the Go application:

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

This compiles the executable file in the Linux environment, ensuring it runs properly in the CloudBase environment.

Step 7: Local Testing (Optional)

Before deployment, you can test the application locally:

go run main.go

Or run the compiled binary file:

./main

After successful testing, you can verify it in the following ways:

  • Access http://localhost:9000/ to view the Hello World message
  • Access http://localhost:9000/myip to view IP information
  • Access http://localhost:9000/health to view the health status

Press Ctrl + C to stop the local server.

Step 8: Deploy to CloudBase HTTP Cloud Function

Preparing Deployment Files

Ensure your project directory contains the following files:

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

Deployment via the Console

  1. Log in to TCB/Cloud Function
  2. Click 'Create New Cloud Function'
  3. Select "HTTP Cloud Function"
  4. Fill in the function name (e.g.: helloworld-go)
  5. Select runtime: Go 1.x
  6. Select the "local upload" method
  7. Package the project files into a zip file and upload (select files for packaging, do not package the root directory folder)
  8. Click "OK" to complete deployment

Deploy via CLI

For more details, please refer to CLI Deploy HTTP Function

Package the project

If manual packaging is required, you can use the following command:

# Create a zip package
zip -r helloworld-golang.zip main scf_bootstrap

Step 9: Access Your Application

After successful deployment, you can refer to Web Client Invocation to set up a custom domain for accessing the

You can test in the following ways:

  • Access the root path to view the Hello World message
  • Access the /myip path to view IP information
  • Access the /health path to check the service status

Frequently Asked Questions

Q: Why must port 9000 be used?

A: CloudBase HTTP cloud functions require the application to listen on port 9000, which is the standard configuration of the platform.

Q: How to view function logs?

A: On the CloudBase Console's cloud function page, click the function name to go to the details page where you can view the runtime logs.

Q: Which Go versions are supported?

A: CloudBase supports Go versions 1.16, 1.17, 1.18, 1.19, and others. It is recommended to use a newer stable version.

Q: How to handle CORS cross-origin issues?

A: Configure cross-origin using Gin's CORS middleware, as shown in the example code.

Q: How to handle long cold startup times for functions?

A: You can reduce cold startup time by decreasing the binary size, optimizing code logic, and using static compilation.

Q: How to perform cross-compilation?

A: Use GOOS=linux GOARCH=amd64 environment variables to perform Linux cross-compilation, ensuring it runs properly in the CloudBase environment.

Q: Why is it necessary to compile into a binary file?

A: The CloudBase cloud function environment runs on a Linux system, requiring compilation into a binary file for the corresponding platform to run properly.

Best Practices

  1. Error Handling: Always add appropriate error handling for HTTP requests.
  2. Response Header Settings: Properly set the Content-Type and other necessary response headers.
  3. Logging: Use the log package to log key information for easier debugging.
  4. Environment Variables: Use os.Getenv() to manage configuration information
  5. Code Structure: For complex applications, it is recommended to split files by feature modules.
  6. Performance Optimization: Use connection pools, caching, and other techniques to improve performance
  7. Security Considerations: Validate input parameters to prevent injection attacks

Next Steps