URL Shortener
Start with URL Shortener
Learn url shortener through an executable example, then connect the small demonstration to production code.
What you’ll learn
- Explain the main purpose of url shortener.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
A URL shortener maps compact identifiers to destination URLs and redirects visitors to the stored destinations. A real service must validate allowed URL schemes, handle ID collisions, protect write APIs and address abuse.
The local implementation stores one mapping in memory and demonstrates the redirect using httptest.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Tools, syntax and practical notes
Full project: implement authenticated creation, URL validation, uniqueness constraints, expiration policy, abuse controls, optional click analytics and database-backed redirects. Test missing IDs and invalid schemes.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
)
func main() {
links := map[string]string{"a1": "https://example.org/learn-go"}
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
code := strings.TrimPrefix(r.URL.Path, "/s/")
destination, ok := links[code]
if !ok {
http.NotFound(w, r)
return
}
http.Redirect(w, r, destination, http.StatusFound)
})
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, httptest.NewRequest("GET", "/s/a1", nil))
fmt.Println("Status:", recorder.Code)
fmt.Println("Location:", recorder.Header().Get("Location"))
}
Output
Status: 302
Location: https://example.org/learn-goTrace what the program does
The short code a1 looks up the saved destination, then http.Redirect sets status 302 and a Location header pointing to the full URL.
Avoid common mistakes
- Never accept javascript: or other unsafe destination schemes when constructing redirects.
- Incrementing IDs must be collision-safe across concurrent instances if used in a real service.
Try it yourself
Add a POST endpoint to create validated short links, a collision-safe ID generator and persistent storage.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced URL Shortener in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.