Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 39 ยท Projects and Practice

Project: A URL Shortener

Build a URL shortener in Gin: short codes with base62, safe URL validation, 301 vs 302 redirects, click counting, caching, a unique-code race and a runnable stand-in.

A URL shortener looks trivial, and that is why it is a favorite project: the interesting parts are hidden in the details. How do you generate short unique codes? Which redirect status? How do you stop people from shortening javascript: links or pointing the service at your own internal network? How do you count clicks without slowing every redirect? This project works through those decisions with Gin.

Gin and GORM are not available in the in-page runner, so the Gin handlers are read-only. The algorithms and the HTTP behaviour (code generation, validation, redirects, counting) run in plain Go below.

Design

Two routes do almost everything:

Route Purpose
POST /api/links Takes {"url": "https://..."} and returns {"code": "b9", "short_url": "https://sho.rt/b9"}
GET /:code Redirects to the original URL and counts the visit
GET /api/links/:code Shows stats (click count, created time)

A wildcard route such as /:code shares the URL root with fixed routes like /api and /healthz (see Routes and HTTP Methods). Recent Gin versions let fixed routes win over the wildcard, but a user must still never be able to claim a short code equal to one of your own paths, so we keep a reserved-word list (api, healthz, admin, ...) and reject those codes.

Generating short codes

Two common strategies:

  1. Random codes. Pick 7 characters from base62 (0-9a-zA-Z), giving 62^7, about 3.5 trillion combinations. Insert; if the unique index reports a duplicate, try again. Codes are unguessable.
  2. Counter plus base62. Use the auto-increment row ID and encode it: ID 125 becomes 21. Codes are short and never collide, but sequential codes are guessable and reveal how many links you have. Shuffle the alphabet or XOR the ID with a secret to disguise it.
Go Base62 encoding of row IDs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

One million links fit in four characters; seven characters cover 3.5 trillion. Decoding validates characters, which also helps reject junk in the URL path before it ever touches the database.

Validating the target URL

Never redirect to whatever string you are given. Parse it and apply rules:

  • Scheme must be http or https. Reject javascript:, data:, file:.
  • A host is required. Limit the length (2,048 characters is a common cap).
  • Reject URLs pointing at your own domain (redirect loops) and, for a service that fetches pages for previews, at private network ranges (127.0.0.1, 10.x, 169.254.169.254): that is server-side request forgery (SSRF).
  • Strip or reject credentials in the URL (https://user:pass@...).
Go URL validation rules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

A string check alone cannot stop DNS tricks (a public name that resolves to a private address). A service that actually fetches the target needs a custom dialer that checks the resolved IP. For a plain redirect service, scheme and host checks are enough.

301 or 302?

  • 301 Moved Permanently is cached by browsers. Redirects become faster and cheaper, but you will not see repeat visits (so clicks are undercounted) and a changed target may not reach cached clients.
  • 302 Found (or 307) is not cached, so every click reaches your server and your counters stay accurate. Most shorteners that offer analytics use 302.

The Gin code

Go
func (h *LinkHandler) Create(c *gin.Context) {
	var req struct {
		URL string `json:"url" binding:"required"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "url is required"})
		return
	}
	target, err := Validate(req.URL)
	if err != nil {
		c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
		return
	}

	for attempt := 0; attempt < 5; attempt++ {
		link := model.Link{Code: randomCode(7), Target: target}
		err = h.db.Create(&link).Error
		if err == nil {
			c.JSON(http.StatusCreated, gin.H{"code": link.Code, "short_url": h.base + "/" + link.Code})
			return
		}
		if !isDuplicateKey(err) {
			break
		}
		// unique index hit: generate another code and retry
	}
	c.JSON(http.StatusInternalServerError, gin.H{"error": "could not create link"})
}

func (h *LinkHandler) Redirect(c *gin.Context) {
	var link model.Link
	if err := h.db.Where("code = ?", c.Param("code")).First(&link).Error; err != nil {
		c.String(http.StatusNotFound, "link not found")
		return
	}
	h.clicks.Inc(link.ID) // never block the redirect on a counter write
	c.Redirect(http.StatusFound, link.Target)
}

Avoid the "check, then insert" pattern for uniqueness: two requests can both see the code as free. Instead let the database's unique index be the judge and retry on a duplicate-key error, as above. See CRUD with GORM and Gin for mapping database errors to responses.

Counting clicks without slowing down

UPDATE links SET clicks = clicks + 1 on every redirect makes hot links contend for one row lock. Better: increment an in-memory counter and flush the totals periodically in a batch.

Go A buffered click counter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

In production a background goroutine calls Flush every few seconds (and once more during graceful shutdown, or counts are lost). For multiple servers, increment in Redis instead. Also cache hot code-to-URL lookups in memory or Redis, since reads vastly outnumber writes.

Extensions

  • Custom aliases (/summer-sale) with a reserved word list and the same unique index.
  • Expiry dates and a soft-disable flag, answering 410 Gone for expired links.
  • Rate limit link creation per user or IP (Rate Limiting and Input Safety).
  • QR code endpoint, and per-day click statistics grouped by referrer.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How many distinct 7-character base62 codes exist?

    Each of the 7 positions has 62 choices, so 62^7.
  2. 2. Why prefer 302 over 301 for a shortener with analytics?

    A cached 301 sends later clicks straight to the target without touching your server.
  3. 3. What is the safe way to guarantee unique codes under concurrent requests?

    Check-then-insert races; the index is the single source of truth.
  4. 4. Which targets must be rejected?

    Non-http schemes enable script injection and private addresses enable SSRF.

Summary

  • Generate codes randomly (retry on duplicates) or by base62-encoding row IDs.
  • Parse and validate targets: http/https only, no credentials, no private hosts, no loops.
  • Use 302 when you want every click counted; 301 when you want caching.
  • Let a unique index guarantee uniqueness, and buffer click counts instead of updating a hot row.

Next: Project: A Blog with Server-Rendered Pages