Earlier this month Google Cloud Functions team finally announced beta support of Go, the runtime uses Go 1.11, which includes go modules as we know.
In this post I am going to show how to write and deploy 2 types of functions: HTTP function and background function.
HTTP functions are functions that are invoked by HTTP requests. They follow the http.HandlerFunc type from the standard library.
In contrast, background functions are triggered in response to an event. Your function might, for example, run every time there is new message in Cloud Pub/Sub service.
The first step is to ensure that you have a Google Cloud Platform account with Billing setup. Remember that there is an always free tier when you sign up for Google Cloud and you could use that too.
Once you have setup your project, the next step is to enable the Google Cloud Functions API for your project. You can do it from Cloud Console or from your terminal using
It will be a simple HTTP function which generates a random number and sends it to Cloud Pub/Sub topic.
Let’s create our topic first:
I will create a separate folder / package for this function.
Our package uses
cloud.google.com/go/pubsub package, so let’s initialize go modules.
If you have external dependencies, you have to vendor them under the library package locally before deploying.
Now it’s time to deploy it:
api is a name,
Send is an entrypoint function,
--trigger-http tells that it is HTTP function. And we also set a PROJECT_ID env var.
The deployment may take few minutes.
HTTP functions can be reached without an additional API gateway layer. Cloud Functions give you an HTTPS URL. After the function is deployed, you can invoke the function by entering the URL into your browser.
Since Google Cloud background functions can be triggered from Pub/Sub, let’s just write a function which will simply log a payload of event triggering it.
Note: we don’t need go modules in consumer.
The deployment part is very similar to HTTP function, except how we’re triggering this function.
Let’s check logs now after execution.
Please share your experience with Google Cloud Functions in Go, are you missing any functionality there, any issues you encountered.
To cleanup let’s delete everything we created: function and pub/sub topic.
This post is a text version of packagemain #15: Google Cloud Functions in Go.