Introduction

URL shorteners are handy tools for converting long and cumbersome URLs into shorter, more manageable ones. In this guide, you'll learn how to build a URL shortener using the Go programming language and Redis, a popular in-memory data store. This project will involve generating short URLs, storing them in Redis, and redirecting users to the original URLs. Sample code is provided at each step to help you understand the process.


Prerequisites

Before you begin, make sure you have Go and Redis installed on your system. You can download and install Go from the official website, and Redis can be obtained from the Redis website or via package managers.


Generating Short URLs

To generate short URLs, you can use a combination of characters or hashing algorithms. Here's an example of generating a random string as a short URL:

package main
import (
"math/rand"
"time"
)
const (
letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
func generateShortURL(length int) string {
b := make([]byte, length)
for i := range b {
b[i] = letterBytes[rand.Intn(len(letterBytes))]
}
return string(b)
}

This code generates a random alphanumeric string of the desired length, which will serve as the short URL.


Storing URLs in Redis

Redis is an excellent choice for storing short URLs as key-value pairs. You can use the short URL as the key and the original URL as the value. Below is an example of storing URLs in Redis using the "github.com/go-redis/redis/v8" package:

package main
import (
"context"
"github.com/go-redis/redis/v8"
)
var redisClient *redis.Client
func init() {
redisClient = redis.NewClient(&redis.Options{
Addr: "localhost:6379", // Redis server address
Password: "", // No password
DB: 0, // Default DB
})
}
func storeURL(shortURL, originalURL string) error {
ctx := context.Background()
return redisClient.Set(ctx, shortURL, originalURL, 0).Err()
}
func getOriginalURL(shortURL string) (string, error) {
ctx := context.Background()
return redisClient.Get(ctx, shortURL).Result()
}

The code initializes a Redis client, provides methods to store and retrieve URLs, and specifies the server's address. You may need to adjust the Redis server settings to match your environment.


Redirecting Users

When users access a short URL, you should redirect them to the original URL. Below is an example of handling URL redirection in a Go web server:

package main
import (
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
shortURL := r.URL.Path[1:] // Remove the leading slash
originalURL, err := getOriginalURL(shortURL)
if err != nil {
http.NotFound(w, r)
return
}
http.Redirect(w, r, originalURL, http.StatusFound)
})
http.ListenAndServe(":8080", nil)
}

This code defines a simple Go web server that listens on port 8080, extracts the short URL from the path, retrieves the original URL from Redis, and performs a redirection.


Conclusion

Building a URL shortener with Go and Redis is a practical project that demonstrates how to generate short URLs, store them in Redis, and redirect users to the original URLs. This guide has provided you with sample code and explanations at each step to help you create your own URL shortening service.


Further Resources

To further explore Go, Redis, and URL shortening, consider these resources: