Matt Davies Stockton Discusses How to Build a Serverless URL Shortener with GO

Introduction

According to Matt Davies Stockton, everyone who has ever been redirected to a link on the internet is familiar with bit.ly. It’s a serverless URL shortener that can shorten large URLs. Let’s check out how you can do the same and create your own serverless shortener with the programming language Go.

 

The Discussion

 

  1. Create the application – Make sure that you have Go v1.16 or higher and AWS SDK installed on your system. Start by cloning the project and changing it to the right directory. Next, use the “cdk deploy” command to deploy the application. After that, you’ll see a list of resources being created and you’ll need to provide confirmation to proceed. This step will start creating the AWS resources necessary for your app.

 

When all resources are created you should have the DynamoDB table, Lambda functions, an API gateway, and a few other resources. Note down the API gateway endpoint in the stack output since you’ll need it later on.

 

  1. Shorten URLs – Start generating shortcodes for a few URLs by passing the original URL as part of an HTTP POST request in the payload body. If everything goes well, you should get HTTP 201 with a shortcode as a JSON payload in the HTTP response. Check the DynamoDB table to confirm the URLs.

 

  1. Use the shortcode to access the URL – Now that the shortcode is generated, it should redirect you to the original URL when you enter it into the address bar of your browser. You can confirm the same by creating an HTTP GET request with the “curl” command. It should return an HTTP 302 response.

 

  1. Set the status – You can enable or disable the created shortcodes and the original URL would be accessible only when the association is kept in an active state. To disable a shortcode you need to create an HTTP PUT request with “curl”. It would work if you’ve used a JSON payload that specifies the status of the shortcode as a path parameter to the API gateway endpoint. If everything goes smoothly, you’ll see an HTTP 204 response.

 

  1. Delete and clean up – To delete a URL along with its shortcode, you can use an HTTP DELETE request along with the shortcode via “curl”. Similar to the previous steps, it should return an HTTP 204 response. This step should also delete the DynamoDB record.

 

After that, you need to delete all the services by using the simple command “cdk destroy”. It destroys the last stack you’ve created. On the other hand, if you want to destroy multiple stacks, you’ll also need to specify the name of the stacks that need to be deleted.

 

Conclusion

Matt Davies Stockton suggests that you use the above-mentioned tips to create a URL shortener by using DynamoDB Go SDK. That way, integrating it with AWS Lambda becomes easy. AWS SDK supports GO and you can use API gateways to create the serverless infrastructure.