Serverless Applications: Google Cloud Functions and Golang

In cloud computing, serverless architecture has emerged as a transformative approach to application development. It eliminates the need to manage servers, allowing developers to focus on building and deploying code without worrying about infrastructure provisioning or maintenance. Google Cloud Functions (GCF) is a powerful serverless platform that simplifies the process of building and deploying cloud-based applications using various programming languages, including Golang, Node.js, Python and Java.

This blog post will explore building a serverless application on the cloud console using GCF and Golang. We'll create a simple HTTP function that receives a JSON payload, processes it, and returns a JSON response.

Golang, also known as Go, is a versatile and efficient programming language developed by Google. Its lightweight syntax, concurrency features, and robust standard library make it well-suited for serverless development. With GCF and Golang, developers can create scalable, highly available applications that respond to events and perform various tasks without the burden of managing servers.

Prerequisites:

  1. Google Cloud Platform (GCP) account

  2. Go SDK installed (download from https://go.dev/)

  3. Basic understanding of Golang syntax and cloud computing concepts

Create a Google Cloud Project


  1. Sign in to your GCP console and create a new project or select an existing one.

  2. Enable the Google Cloud Functions API for your project.

    1. Go to the Google Cloud Platform Console: https://console.cloud.google.com/ and sign in to your Google Cloud account.

    2. Select the project for which you want to enable the API.

    3. Click the Navigation menu (three horizontal bars) in the top left corner of the console.

    4. Select APIs & Services.

    5. Click Enable APIs and Services.

    6. In the search bar, type Cloud Functions API and press Enter.

    7. Select Cloud Functions API and click Enable.

    8. Click Continue.

Create your function

Create a directory in your working directory for the function code:

mkdir ~/cloud-functions
cd ~/cloud-functions

Create a file called hello-function.go in the helloworld directory with the following contents.

// Package helloworld provides a set of Cloud Functions samples.

package helloworld

import (
        "encoding/json"
        "fmt"
        "html"
        "net/http"

        "github.com/GoogleCloudPlatform/functions-framework-go/functions"
)

func init() {
    functions.HTTP("HelloHTTP", HelloHTTP)
}

// HelloHTTP is an HTTP Cloud Function with a request parameter.
func HelloHTTP(w http.ResponseWriter, r *http.Request) {
    var d struct {
        Name string `json:"name"`
    }
    if err := json.NewDecoder(r.Body).Decode(&d); err != nil {
        fmt.Fprint(w, "Hello, World!")
        return
    }
    if d.Name == "" {
        fmt.Fprint(w, "Hello, World!")
        return
    }
    fmt.Fprintf(w, "Hello, %s!", html.EscapeString(d.Name))
}

The provided Go code is an example of an HTTP Cloud function for Google Cloud. Here's an explanation of the code:

  • The package helloworld line defines the package name for this Go file.

  • Next, several libraries are imported. These include "encoding/json" for encoding and decoding JSON data, "fmt" for output formatting, "html" for HTML escaping, "net/http" for HTTP server-related functions, and "github.com/GoogleCloudPlatform/functions-framework-go/functions" for Google Cloud's functions framework for Go.

  • The init() function is a special function in Go. It gets called when the package is initialized. Inside this init() function, functions.HTTP("HelloHTTP", HelloHTTP) is registering the function HelloHTTP to be called when an HTTP request is made with the path "/HelloHTTP".

  • The main function here is HelloHTTP(). It takes two arguments, an http.ResponseWriter and an http.Request. It's the handler function for HTTP requests.

  • In HelloHTTP(), it first declares a struct with a Name field. It then tries to decode the JSON body of the incoming HTTP request into this struct.

    • - If it cannot decode the JSON, it responds with the message "Hello, World!".

    • - If it can decode the JSON but no name is given, it also responds with "Hello, World!".

    • - If a Name is given in the request, it greets with "Hello, Name!".

  • The Name is HTML-escaped before it is put into the output string to prevent HTML injection attacks. 

This function is designed to be deployed in a Google Cloud Function, which HTTP requests can trigger.

Track dependencies

To keep track of your dependencies, generate a go.mod file:

cd ~/helloworld
go mod init cloud-functions/helloworld
go mod tidy

Deploy the Golang Function

gcloud functions deploy go-http-function \
    --gen2 \
    --runtime=go121 \
    --region=REGION \
    --source=. \
    --entry-point HelloHTTP \
    --trigger-http \
    --allow-unauthenticated

This command will deploy a Go Cloud Function named go-http-function to the us-central1 region. HTTP requests will trigger the function and will be accessible to unauthenticated users.

Here are some additional details about the flags:

  • The --gen2 flag is optional. If you do not specify this flag, your Cloud Function will be deployed using the first-generation Cloud Functions runtime.

  • The --runtime flag is required. You must specify the runtime you want to use for your Cloud Function.

  • The --region flag is required. You must specify the region where you want your Cloud Function to be deployed.

  • The --source flag is required. You must specify the source code for your Cloud Function.

  • The --entry-point flag is required. You must specify the entry point for your Cloud Function.

  • The --trigger-http flag is optional. If you do not specify this flag, HTTP requests will not trigger your Cloud Function.

  • The --allow-unauthenticated flag is optional. If you do not specify this flag, your Cloud Function will only be accessible to authenticated users.


Test the Function

Once the function has been deployed, record the URI from the output of the gcloud functions deploy command or use the following command to retrieve it:

gcloud functions describe go-http-function \
    --region REGION

  1. Replace REGION with the where you deployed your function (for example, us-central1).

  2. Visit this URL in your browser. The function returns a "Hello World!" message.
    You can also find this URL in the Google Cloud console. 

  3. Go to the Cloud Functions Overview page, and click the name of your function to open its Function details page. Open the TESTING tab to test your function right from the console.

Congratulations! You have successfully built and deployed a simple serverless application with Google Cloud Functions using Golang. This is just the beginning of your journey into serverless computing. Explore the various features and capabilities of Google Cloud Functions to create more complex and scalable serverless applications.

Previous
Previous

Revolutionizing Environmental Conservation in Africa with Bioinformatics, AI, and Cloud Technology

Next
Next

AI for Everyone: Free Courses