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:
- 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. - Shorten URL Function: The
shortenURL()
function generates a random string of 6 characters, which is used as the short URL. It uses themath/rand
package to generate random characters from a defined set (letters and digits) and then stores the long URL in theurlMap
with the corresponding short URL as the key. - 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.
- 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:
- Ensure that you have Go installed on your machine. You can download it from the official Go website: https://golang.org/dl/.
- Save the Go code in a file, for example,
url_shortener.go
. - Open a terminal and navigate to the directory containing the Go file.
- Run the program by typing the following command:
go run url_shortener.go
- Open a web browser and navigate to
http://localhost:8080/shorten
. - Send a POST request to the /shorten endpoint with a long URL (you can use tools like Postman or cURL for this).
- After getting the shortened URL, access it via the browser, and it will redirect you to the original URL.