Introduction
Previously, I wrote a guide on deploying a NodeJS TypeScript Function to Google Cloud Functions (GCF) and provided some basic information about GCF, which you can check out here. In this article, I'll walk you through a simple way to deploy a Go Function to GCF.
Prerequisites
Before we dive in, make sure you:
- Have a Google Cloud account and have enabled Cloud Functions.
- Have a basic understanding of Go. You can refer to this guide to set up the Go project used in this article.
Implement Cloud Function
After setting up your Go project, rename the module in the `go.mod` file to follow this format: `example.com/moduleName`. This is required to deploy a Go Function.
Next, update the content of the `main.go` file as follows:
package packageName
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
)
// get method
func GoCloudFunction1(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "GoCloudFunction")
}
type ResponseData struct {
Name string `json:"name"`
Time time.Time `json:"time"`
}
// get method with query params
func GoCloudFunction2(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
query := r.URL.Query()
names, present := query["name"] // get query params
if !present || len(names) == 0 {
json.NewEncoder(w).Encode(ResponseData{Time: time.Now()})
return
}
name := strings.Join(names, ",")
json.NewEncoder(w).Encode(ResponseData{Name: name, Time: time.Now()})
}
// post method with body request json data
func GoCloudFunction3(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
var res ResponseData
if err := decoder.Decode(&res); err != nil {
http.Error(w, "Invalid JSON data", http.StatusBadRequest)
return
}
defer r.Body.Close()
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
json.NewEncoder(w).Encode(ResponseData{Name: res.Name, Time: time.Now()})
}
You can see that I've defined three functions:
- A regular GET method
- A GET method that uses query parameters (like `http://host?param=valueParam`)
- A POST method that uses a JSON body request
To deploy the Go Function, follow these steps:
gcloud functions deploy functionName --runtime=go121 --region=asia-southeast1 --trigger-http --allow-unauthenticated
- --runtime: Use the command `gcloud functions runtimes list` to see the list of runtimes supported by Cloud Functions.
- --region: Optional, replace with your region.
- --allow-unauthenticated: This makes your function public. Without this, authentication is required to use the function.
Deploy each function one by one. If the deployment is successful, the result will look like this.
To view the logs during the application's running
gcloud functions logs read --limit={number} --region={region} {function name}
Don't hesitate to leave your thoughts in the comments section, and remember to like, share, and follow for more insightful content in the future!
Comments
Post a Comment