In-Memory URL Shortener Service
Build a small URL shortener service in Go using only the standard library: send it a long URL (through an API or a simple web form) and get a short code back, then anyone visiting the short link is redirected to the original, and each visit is counted. Links are stored in memory in a map protected by a mutex, since many requests can arrive at the same time. It's a great first Go web project: you'll learn net/http handlers and routing, reading form and JSON input, redirects and status codes, generating random codes, making shared data safe with sync.Mutex, HTML templates, and testing handlers with httptest.
- Estimate
- ~7h
- Steps
- 6
- Completed by
- 0
- Proposed by
- codeseed.app
net/http · sync
Project roadmap
- 01
Set up the HTTP handlers
~1hRun go mod init and create main.go with an http.ServeMux: POST /shorten, GET /{code} (using Go 1.22's path patterns), GET /stats/{code} and GET / for a form. Start the server on a port from a flag, and return placeholder responses for now. Done when: each route answers with curl.
- 02
Store links safely
~1.5hCreate a Store type with a map from code to a link record (original URL, created time and clicks) and a sync.RWMutex. Generate 6-character codes from letters and digits with crypto/rand, trying again if a code already exists. Validate URLs with net/url (http or https, and a host). POST /shorten accepts JSON {"url": "..."} and returns the code and short URL, or 400 for invalid URLs. Done when: shortening valid URLs returns codes, and invalid ones get 400.
- 03
Redirect visitors
~1hIn GET /{code}, look up the link, increase its click count (while holding the lock), and redirect with http.Redirect and status 302. Return 404 with a friendly message for unknown codes. Done when: opening a short link in the browser lands on the original page.
- 04
Add a web form
~1hServe a page from an html/template with a form to submit a URL, which posts to a handler that shows the resulting short link (or the error) on the same page. The template escapes the URL automatically, so pasted HTML can't run. Done when: a URL can be shortened from the browser form.
- 05
Show click stats
~1hMake GET /stats/{code} return the original URL, creation time and click count as JSON, and show the stats on the form page after shortening. Done when: stats show the correct click count after a few visits.
- 06
Test it
~1.5hWrite tests with httptest.NewRecorder and httptest.NewServer: shortening valid and invalid URLs, redirects (checking the status and Location header), unknown codes, stats, and many goroutines visiting the same link at once to check the click count and run with -race. Done when: go test -race ./... passes.
Ready to build this?
Get a GitHub repo and start building. Your AI reviewer checks each step as you go.
Tech stack