Simple URL shortener service implemented in Go. This repo contains a small HTTP API to shorten URLs and redirect short codes to original URLs. The service uses an in-memory storage implementation and is packaged with Docker and Docker Compose.
Quick links (workspace)
-
Files:
-
Important symbols:
Requirements
- Docker & Docker Compose
- (Optional) Go 1.24 or newer for running tests locally (module set in go.mod)
How to run the code
- Run with Docker Compose (recommended)
- Build and start (background):
docker compose up --build -d- Check container logs:
docker compose logs -f app- Stop and remove:
docker compose downNotes:
- The service listens on port 8080 (host port mapped in docker-compose.yaml).
- Base URL is set via the
BASE_URLenvironment variable in docker-compose.yaml and defaults tohttp://localhost:8080. The server code that reads these is in cmd/server/main.go.
- Run locally (without Docker)
- With Go installed (recommended for development):
# from repo root
go run ./cmd/server
# or build binary
go build -o urlshort ./cmd/server
./urlshort- Environment variables:
- PORT (default 8080)
- BASE_URL (default http://localhost:8080)
The app is wired in cmd/server/main.go which creates the storage
storage.NewMemoryStorage, the serviceservice.NewURLServiceand the handlershandler.NewHandler.
- Run tests
- Locally (requires Go toolchain):
go test ./... -vTests are in test/service_test.go and test/handler_test.go.
- Inside a container (no local Go):
docker run --rm -v "$(pwd):/app" -w /app golang:1.24 go test ./... -v- Manual / API testing (curl or Postman)
- Shorten a URL (POST):
curl -s -X POST -H "Content-Type: application/json" \
-d '{"url":"https://example.com"}' \
http://localhost:8080/api/shorten
# -> {"short_url":"http://localhost:8080/EAaArVRs","long_url":"https://example.com"}- Inspect redirect headers (HEAD):
curl -I http://localhost:8080/<shortCode>
# -> HTTP/1.1 302 Found, Location: https://example.com- Follow redirect (GET):
curl -L http://localhost:8080/<shortCode>Postman:
- Create environment variable
base_url = http://localhost:8080. - POST {{base_url}}/api/shorten with JSON body
{ "url": "https://example.com" }. - For redirect request GET {{base_url}}/{{short_code}} — disable auto-follow redirects to inspect the 302 Location header.
Behavior summary
- POST /api/shorten: returns JSON
{ "short_url": "...", "long_url": "..." }. Implemented inhandler.Handler.ShortenURLand usesservice.URLService.ShortenURL. - GET /{shortCode}: returns HTTP 302 with Location header on success. Implemented in
handler.Handler.RedirectURLand resolves viaservice.URLService.GetLongURL. - Storage is in-memory via
storage.NewMemoryStorage— restarting the app clears stored mappings.