What?

Showing my Medium article list on a static website using an AWS Lambda function built with Golang and the AWS API Gateway.

Why?

I was building a virtual homepage using GitHub pages and wanted to show the list of articles I’ve written on medium. There is no method for this in the official Medium API, but this url (https://medium.com/@username/latest?format=json) does return a list of articles for a user in JSON format.

This provides a conventient way to retrieve the data, but CORS prevents it from being loaded in the frontend app within the browser. I could proxy this information through a server but I did not want to create and manage one for this, which is why I was using GitHub pages in the first place.

For this, AWS Lambda comes to the rescue! With AWS Lambda you can write a function in any of their supported languages. You can then upload it to the Lambda service either through CLI or the AWS browser console. There is no need to provision or manage a server. It’s also very cheap.

How?

First we will write the function in a file locally, then we’ll create a new Lambda function and upload our local file to it. To access the Lambda function, we’ll create an AWS API Gateway APT to call from our frontend. The full file I used is below, followed by an explanation.

We create a file called main.go and import github.com/aws-lambda-go/events and github.com/aws-lambda-go/lambda . We define two structs, Response and Postdata , to parse data from the JSON response of our API call.

Next we define a function handler which takes two parameters: context (runtime information) and request (information about the API call from the AWS API Gateway). We return a response to send back to the API Gateway caller and an error .

Within the function we make a GET request using the net/http library to the Medium URL (line 33) and convert it to a string (line 40). Then we remove some unwanted text using from the response by using (Medium adds th ese to avoid JSON hijacking) at line 45. Then we decode the JSON (line 49) and again encode only the part we need back to JSON (line 51). Finally, we return the response.

The main function is the entry point, and we call the Start function from the lambda package to run our handler function.

Next, we’ll build an executable binary for a linux machine GOOS=linux go build -o main main.go and zip the file zip main.zip main .

Now, let’s create the Lambda function from the AWS browser console. Once logged in, navigate to the Lambda section.