Building a URL Shortener
This tutorial guides you through creating a URL shortener using DiceDB, a key-value store, with Go. We’ll set up endpoints to generate short URLs and redirect them to the original URLs.
Prerequisites
- Go (version 1.18 or later): Download Go
- DiceDB: A DiceDB server running locally. Refer to the DiceDB Installation Guide if you haven’t set it up yet.
Setup
1. Install and Run DiceDB
Start a DiceDB server using Docker:
This command pulls the DiceDB Docker image and runs it, exposing it on port 7379
.
2. Initialize a New Go Project
Create a new directory for your project and initialize a Go module:
3. Install Required Packages
Install the DiceDB Go SDK and other dependencies:
Understanding DiceDB Commands
We’ll use the following DiceDB commands:
SET
Command
Stores a key-value pair in DiceDB.
- Syntax:
SET key value [expiration]
key
: Unique identifier (e.g., short URL code)value
: Data to store (e.g., serialized JSON)expiration
: Optional; time-to-live in seconds (use0
for no expiration)
GET
Command
Retrieves the value associated with a key.
- Syntax:
GET key
key
: Identifier for the data to retrieve
Writing the Code
Create a file named main.go
and add the following code:
-
main.go
:
Explanation
1. Initialize the DiceDB Client
We set up the DiceDB client in the init
function:
2. Create Short URL Endpoint
- Input Validation: Ensures the
long_url
field is present. - Short ID Generation: Uses
uuid
to create a unique 8-character ID. - Data Serialization: Converts the
URL
struct to JSON. - Data Storage: Saves the JSON data in DiceDB with the
Set
command. - Response: Returns the generated short URL.
3. Redirect to Original URL Endpoint
- Data Retrieval: Fetches the URL data from DiceDB using the
Get
command. - Data Deserialization: Converts JSON back to the
URL
struct. - Redirection: Redirects the user to the
LongURL
.
4. Start the Server
The main
function sets up the routes and starts the server on port 8080
.
Running the Application
1. Start the Go Application
This will start the application server on port 8080 by default, you should see output similar to
2. Ensure DiceDB is Running
Ensure your DiceDB server is up and running on port 7379
.
Testing the application
1. Shorten URL:
Using curl
:
Response:
2. Redirect to Original URL:
Using curl
:
Using a Browser: Navigate to:
You should be redirected to https://example.com
.