Go
Overview
The Go runtime leverages the inherent performance strength of compiled languages to provide efficient backend floating-point operations capabilities, supporting the standard library
net/http and mainstream Web frameworks such as Gin, Echo, Fiber, and Chi, making it suitable for building high-performance API services.
Advantages
High performance runtime environment: The inherent performance advantage of compiled languages, fast startup, and low memory usage.
Full-stack development experience: No need to separate frontend and backend projects, can complete development and deployment in the same project.
Routing as a service: In Handler mode, define API routing through the file system, manage backend logic the same as a frontend page.
Free choice of framework: Support mainstream Web frameworks like Gin, Echo, Fiber, and Chi, and also support the standard library
net/http.Zero configuration build: Automatically detect frameworks, automatically process route mapping, and automatically cross-compile without manual configuration.
Development Mode
Go functions provide two development modes. You can choose one of them based on project requirements. Mixed use is not allowed.
Mode | Scenarios | Routing Mode | Framework Dependency |
Handler mode | Simple API, Serverless style | File system route (file as route) | No (pure standard library) |
Framework mode | Complete Web application, RESTful API | Built-in framework route | Gin, Echo, Fiber |
Getting Started
Handler Mode - Example
Create new
hello.go in the ./cloud-functions/ directory of the project.// ./cloud-functions/hello.gopackage handlerimport ("encoding/json""net/http")func Handler(w http.ResponseWriter, r *http.Request) {w.Header().Set("Content-Type", "application/json")json.NewEncoder(w).Encode(map[string]string{"message": "Hello from Go Functions on EdgeOne Pages!",})}
Note:
In handler mode, each
.go file needs to export a handler function. The export function must comply with the http.HandlerFunc signature type. The function name can be any valid Go export function name.
Framework Mode - Gin Framework Example
Zero configuration, out-of-the-box: The core idea of Framework mode is direct use of native Framework writing style without any adaptation code. Just write code normally according to the Framework's official documentation, and the platform will automatically perform all adaptation work like port adaptation and path mapping during build.
// ./cloud-functions/api.gopackage mainimport ("net/http""github.com/gin-gonic/gin")func main() {r := gin.Default()// REST API v1 groupv1 := r.Group("/v1"){v1.GET("/hello", func(c *gin.Context) {c.JSON(http.StatusOK, gin.H{"message": "Hello from Gin on EdgeOne Pages!",})})users := v1.Group("/users"){users.GET("", listUsersHandler)users.GET("/:id", getUserHandler)users.POST("", createUserHandler)}}r.Run(":9000")}
Note:
The entry file name
api.go determines that front-end access needs to add the /api prefix. If the entry file name is index.go, no additional prefix is required.
Routing
The Go function generates access routes based on the directory structure under
/cloud-functions in handler mode. You can create subdirectories at any level under the /cloud-functions directory in the project repository. See the example below....cloud-functions├── index.go├── hello-pages.go├── helloworld.go├── api├── users├── list.go├── geo.go├── [id].go├── visit├── index.go├── [[default]].go...
The above directory file structure will generate the following routes after platform construction by EdgeOne Pages. These routes map Pages URLs to the
/cloud-functions file. When a client accesses the URL, it will trigger the corresponding file code to run:File path | Routing |
/cloud-functions/index.go | example.com/ |
/cloud-functions/hello-pages.go | example.com/hello-pages |
/cloud-functions/helloworld.go | example.com/helloworld |
/cloud-functions/api/users/list.go | example.com/api/users/list |
/cloud-functions/api/users/geo.go | example.com/api/users/geo |
/cloud-functions/api/users/[id].go | example.com/api/users/1024 |
/cloud-functions/api/visit/index.go | example.com/api/visit |
/cloud-functions/api/[[default]].go | example.com/api/books/list,example.com/api/books/1024,example.com/api/... |
Note:
The trailing slash in the route is optional. /hello-pages and /hello-pages/ will be routed to /cloud-functions/hello-pages.go.
If a Go function route conflicts with a static resource route, client requests will be routed to the static resource preferentially.
Route is case-sensitive. /helloworld will be routed to /cloud-functions/helloworld.go, not allowed to route to /cloud-functions/HelloWorld.go.
Dynamic Routing
Cloud Functions supports dynamic routing. In the above example, the first-level dynamic path is /cloud-functions/api/users/[id].go, and the multi-level dynamic path is /cloud-functions/api/[[default]].go. See the following usage for reference:
File path | Routing | match |
/cloud-functions/api/users/[id].go | example.com/api/users/1024 | Yes |
| example.com/api/users/vip/1024 | No |
| example.com/api/vip/1024 | No |
/cloud-functions/api/[[default]].go | example.com/api/books/list | Yes |
| example.com/api/1024 | Yes |
| example.com/v2/vip/1024 | No |
Framework route
In Framework mode, the route is fully managed by the framework itself. You just need to register normally in the native route writing style of the framework. The platform will not analyze or intervene in the internal route definition of the framework, but generate a catch-all rule to forward all requests matched to the Go service.
The entry file name determines the URL prefix:
Entry File Name | URL Prefix | Front-end Call Path Example | Framework Internal Routing |
index.go | / (no prefix) | /v1/hello | /v1/hello |
main.go | /main | /main/v1/hello | /v1/hello |
api.go | /api | /api/v1/hello | /v1/hello |
Note:
When the entry file is not index.go, front-end access needs to add the filename prefix, but the internal routing of the framework does not need to be modified. The prefix is removed upon request arrival at the framework. Your skeleton code remains in the native writing style and does not need to perceive the path mapping of the platform.
Function Handlers
Using Function Handlers can create custom request handlers for Pages and define RESTful APIs to implement a full-stack application. In Handler mode, each
.go file needs to export a function that complies with the http.HandlerFunc signature.Basic Usage
The Handler function receives both parameters
http.ResponseWriter and *http.Request. You can process various HTTP requests with the standard library.// ./cloud-functions/api/hello.gopackage handlerimport ("net/http")func Handler(w http.ResponseWriter, r *http.Request) {w.Header().Set("Content-Type", "text/plain")w.Write([]byte("Hello, world!"))}
Handle Multiple Request Methods
Use
r.Method to judge the request method and implement different processing logic with switch:// ./cloud-functions/api/users/index.gopackage handlerimport ("encoding/json""io""net/http")func Handler(w http.ResponseWriter, r *http.Request) {w.Header().Set("Content-Type", "application/json")switch r.Method {case http.MethodGet:json.NewEncoder(w).Encode(map[string]string{"message": "Hello World"})case http.MethodPost:body, err := io.ReadAll(r.Body)if err != nil {http.Error(w, "Failed to read body", http.StatusBadRequest)return}defer r.Body.Close()var data map[string]interface{}json.Unmarshal(body, &data)w.WriteHeader(http.StatusCreated)json.NewEncoder(w).Encode(map[string]interface{}{"message": "Created", "data": data})case http.MethodDelete:w.WriteHeader(http.StatusNoContent)default:http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)}}
Handler Function Parameter Description
The Handler function receives both parameters, providing complete request and response operation capabilities:
Parameter/Property | Type | Description |
r.URL.Path | string | Request path |
r.URL.Query() | url.Values | query parameter |
r.Method | string | HTTP request method (GET, POST) |
r.Header | http.Header | Request header. |
r.Body | io.ReadCloser | Request body input stream |
w.Header() | http.Header | Set response header |
w.WriteHeader(code) | method | Send HTTP Status Code |
w.Write([]byte) | method | Write to response body |
Retrieve Query Parameters
// ./cloud-functions/api/search.gopackage handlerimport ("encoding/json""net/http")func Handler(w http.ResponseWriter, r *http.Request) {// Parse query parametersquery := r.URL.Query()name := query.Get("name")if name == "" {name = "Guest"}w.Header().Set("Content-Type", "application/json")json.NewEncoder(w).Encode(map[string]string{"hello": name,})}
Dependency Management
Go Modules
Go functions use standard Go Modules for dependency management. The
cloud-functions directory must contain a go.mod file:cloud-functions/├── go.mod├── go.sum├── hello.go└── api/└── index.go
Initialize Module
If
go.mod is not created, execute under the cloud-functions directory:cd cloud-functionsgo mod init my-project
Adding Dependencies
Use
go get to add a third-party dependency:go get github.com/gin-gonic/gingo get github.com/go-chi/chi/v5
Or reference
go mod tidy in code and execute afterwards to automatically detect and install required dependencies:go mod tidy
go.mod Example
module my-projectgo 1.26require (github.com/gin-gonic/gin v1.10.0)
Note:
The platform will automatically execute cross-compilation (
GOOS=linux GOARCH=amd64) during build without manual configuration of the compilation target. Use local Go Environment to debug normally during local development.
Sample Template
Go Handler template:
preview address: https://go-handler-template.edgeone.app
Source code address: https://github.com/TencentEdgeOne/go-handler-template
Use Gin framework:
preview address: https://go-gin-template.edgeone.app
Source code address: https://github.com/TencentEdgeOne/go-gin-template
Use Echo framework:
preview address: https://go-echo-template.edgeone.app
Source code address: https://github.com/TencentEdgeOne/go-echo-template
Use Chi framework:
preview address: https://go-chi-template.edgeone.app
Source code address: https://github.com/TencentEdgeOne/go-chi-template