Example Netlify Function in Go

Netlify, the hosting and web platform, allows you to create "functions" along with their CDN. These functions are hosted on AWS’ Lambda and can be accessible via a URL. So you can create static sites, with extra ability and dynamism (like we use on this site).

We wanted to share a post giving an example how to write one of these functions in Go. The aim of the code (below) is to return the version of golang.

Setup

  1. We installed the Netlify cli to make our lives a little easier.

  2. Create our new function, we called it go-version

    1
    
    netlify functions:create
    
  3. Update the code (see below for file path and code)

  4. You can test it

    1
    
    netlify functions:serve
    
    1
    
    curl localhost:9999/.netlify/functions/go-version/
    

Example

⚡ Latest Go Version = GOVERSION

(Called dynamically through our function)

Code

In the code we setup a handler to listen for incoming requests using lambda.Start(). We’ve added the getLatestVer() to then get the data to return.

.netlify/functions/go-version/main.go

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package main

import (
    "context"
    "io/ioutil"
    "net/http"
    "strconv"

    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-lambda-go/lambda"
)

func handler(ctx context.Context, request events.APIGatewayProxyRequest) (*events.APIGatewayProxyResponse, error) {
    version := getLatestVer()
    return &events.APIGatewayProxyResponse{
        StatusCode: 200,
        Headers: map[string]string{
            "Content-Type":   "text/plain",
            "Content-Length": strconv.FormatInt(int64(len(version)), 10),
            "Cache-Control":  "public, max-age=86400",
        },
        Body:            version,
        IsBase64Encoded: false,
    }, nil
}

func getLatestVer() string {
    version := "?"
    resp, err := http.Get("https://go.dev/VERSION?m=text")
    if err != nil {
        return version
    }
    resBody, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return version
    }
    return string(resBody)
}

func main() {
    lambda.Start(handler)
}