Dancing gopher with Cloud Functions

The Beta support for Go 1.11 on Google Cloud Functions has been announced last week. Here are a few details about the Dancing Gopher factory function that I tweeted about.

First, it’s easier to have some code already working on my local machine, before throwing it to GCF. A single source file is enough for a small sample like this one.

My program does basically 4 things:

  • Read a GIF file
  • Change the fur color
  • Add a caption inside each frame
  • Write the updated GIF file

I can start with a command-line Go program (gist):

Local program (abridged)

It works, yay.

The GIF codec is in the standard library. I achieve the fur color change (2 color values) by just modifying the indexed color Palette, instead of accessing the pixels:

A Palette can be used as a colored lens…

Writing some text in an image is not part of the stdlib. However there is a basicfont package in golang/x, let’s use it.

The program doesn’t look like serverless magic though. It reads/writes on the local file system. And values for parameters Text and Color are hard-coded, yuck!

Let’s turn this into an idiomatic Go server (gist):

Web server (abridged)

The server could read from its filesystem, however the next steps will be more straightforward for me if I copy the original GIF to Cloud Storage, make it public, and let my handler read it from its public URL.

My local server is now very close to the format of a Google Cloud Function, except 2 things:

  • the package can’t be “main”
  • there must not be any “main” func
Turning the code into “just a Function”

I can now create a new Function in the GCP web console by copy-pasting my file:

I specify the name of my handler “MakeGif” and hit [SAVE], and a minute later my server is ready to produce dancing gophers. This is a single Function at a single URL, not a full webapp backend!

As you can see, deploying a small piece of code to Cloud Functions is quite simple. My example could equivalently be deployed to App Engine, through a slightly different workflow.

Note that when redeploying a Function, the old version will still be serving for a minute or so, and only then will the new version take over.

Original dancing gopher animation by Egon Elbre