Golang
Golang

 

 

Introduction

In this tutorial, we will demonstrate how to create a simple URL shortener using the Go programming language.
URL shorteners are a great way to make long and unwieldy URLs much more manageable, and they are widely used
on the web for convenience and better sharing experiences. This simple application will allow users to input
long URLs and retrieve short versions, which will redirect to the original URLs.

Objective

The objective of this program is to create a basic URL shortening service. It will:

  • Accept a long URL as input.
  • Generate a shortened version of that URL.
  • Redirect users from the shortened URL back to the original long URL.

Let’s dive into the code implementation of this URL shortener.

Go Program Code

package main

import (
    "fmt"
    "net/http"
    "math/rand"
    "time"
    "strings"
)

var urlMap = make(map[string]string)

func shortenURL(longURL string) string {
    // Generate a random string of length 6
    rand.Seed(time.Now().UnixNano())
    chars := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    shortURL := ""
    for i := 0; i < 6; i++ {
        shortURL += string(chars[rand.Intn(len(chars))])
    }
    urlMap[shortURL] = longURL
    return shortURL
}

func redirectHandler(w http.ResponseWriter, r *http.Request) {
    shortURL := strings.TrimPrefix(r.URL.Path, "/")
    longURL, exists := urlMap[shortURL]
    if exists {
        http.Redirect(w, r, longURL, http.StatusFound)
    } else {
        http.Error(w, "URL not found", http.StatusNotFound)
    }
}

func main() {
    // Set up basic routes
    http.HandleFunc("/shorten", func(w http.ResponseWriter, r *http.Request) {
        if r.Method == "POST" {
            longURL := r.FormValue("url")
            shortURL := shortenURL(longURL)
            fmt.Fprintf(w, "Shortened URL: http://localhost:8080/%s\n", shortURL)
        } else {
            http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
        }
    })
    
    http.HandleFunc("/", redirectHandler)

    // Start the server
    fmt.Println("Server is running on http://localhost:8080/")
    http.ListenAndServe(":8080", nil)
}

Explanation of the Program Structure

This program consists of several key components:

  1. URL Map: A global map called urlMap is used to store the relationship between short URLs and their original long URLs. This is implemented as a key-value pair, where the key is the short URL, and the value is the long URL.
  2. Shorten URL Function: The shortenURL() function generates a random string of 6 characters, which is used as the short URL. It uses the math/rand package to generate random characters from a defined set (letters and digits) and then stores the long URL in the urlMap with the corresponding short URL as the key.
  3. HTTP Handlers: Two handlers are defined:
    • /shorten accepts POST requests, where the long URL is received, shortened, and returned to the user.
    • / handles the redirection. When a short URL is accessed, the program looks up the original long URL in the urlMap and performs an HTTP redirect to the original URL.
  4. Server: The program starts an HTTP server on port 8080, and it listens for incoming requests. It uses the http.ListenAndServe function to begin accepting and handling requests.

How to Run the Program

To run the program, follow these steps:

  1. Ensure that you have Go installed on your machine. You can download it from the official Go website: https://golang.org/dl/.
  2. Save the Go code in a file, for example, url_shortener.go.
  3. Open a terminal and navigate to the directory containing the Go file.
  4. Run the program by typing the following command:
    go run url_shortener.go
  5. Open a web browser and navigate to http://localhost:8080/shorten.
  6. Send a POST request to the /shorten endpoint with a long URL (you can use tools like Postman or cURL for this).
  7. After getting the shortened URL, access it via the browser, and it will redirect you to the original URL.
© 2025 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)