Features: - URL shortener with QR codes, click tracking, deduplication, rate limiting - Pastebin with Markdown rendering, access tokens, raw view - Admin dashboard: dark theme, stats bar, Quick Links tiles with favicons, card-based layout, format/token badges, empty states - CSRF protection, bcrypt auth, in-memory sessions, security headers - Pure-Go SQLite (no CGo), single self-contained binary Deploy: - deploy/install.sh: auto-detects systemd vs SysV init - deploy/urlshort.service: hardened systemd unit - deploy/urlshort.init: SysV init script for older Ubuntu Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
17 KiB
urlshort
A lightweight, single-binary URL shortener and pastebin built in Go. Designed to run on a Raspberry Pi Zero (512MB RAM, single-core ARM) with minimal dependencies and no external runtime requirements.
Features
URL Shortener
- Public: Anyone can shorten a URL — no account required
- Auto-scheme: Submitting
google.comautomatically becomeshttps://google.com - Deduplication: Submitting the same URL a second time returns the existing short link
- QR codes: Server-side SVG QR codes generated for every short link (crisp, no CDN)
- Click tracking: Every redirect increments the click counter
- IP rate limiting: Anonymous users limited to 1 short link per second; admin is never limited
- Short slugs: 3-character base-36 auto-generated (
a-z,0-9); up to 64 characters for custom (admin only)
Admin Dashboard
- Login protected with bcrypt-hashed password; centered dark-theme login card
- Dark UI throughout all admin pages (login, dashboard, edit forms, pastes)
- Stats bar: live counts of My Links, Anonymous Links, and Quick Links at a glance
- My Links card: links the admin created, with edit/delete and click counts
- Anonymous Links card: links created by unauthenticated users, also manageable
- Quick Links tile grid: Top 20 most-clicked admin links displayed as tiles with favicon, destination hostname, and click count; one click to open
- Pastes list: format and token-status badges; empty states with guidance
- Create links with custom slugs (blocked for anonymous users)
- Edit slug and destination URL
Pastebin
- Admin: Create, edit, delete pastes
- Public: Read-only access; optionally protected by a 12-character access token
- Formats: Markdown (GitHub-Flavored, rendered server-side) and plain text
- Raw view: Append
?raw=1to any paste URL fortext/plainoutput - Copy button: One-click clipboard copy in the paste viewer
Security
- CSRF protection on every state-changing POST (double-submit cookie pattern)
crypto/subtle.ConstantTimeComparefor CSRF and paste token comparisons- Session cookie:
HttpOnly,SameSite=Lax, conditionallySecurewhen behind HTTPS proxy - Security headers on all responses:
X-Frame-Options: DENY,X-Content-Type-Options: nosniff,Referrer-Policy - Input length limits: URLs 2048 chars, paste content 512 KB
- URL scheme re-validated before every redirect (defense in depth)
- In-memory sessions with hourly cleanup goroutine
Project Layout
urlshort/
├── main.go # Entry point; flag parsing; --hash-password helper
├── config.toml # Runtime configuration (port, admin creds, db path)
├── go.mod / go.sum
├── Makefile
├── deploy/
│ ├── install.sh # Install script (auto-detects systemd vs SysV)
│ ├── urlshort.service # systemd unit file (Ubuntu 15.04+)
│ └── urlshort.init # SysV init script (Ubuntu 14.04 and older)
├── data/
│ └── urls.db # SQLite database (auto-created on first run)
└── internal/
├── config/
│ └── config.go # TOML config loader; Config struct
├── db/
│ └── db.go # SQLite open/migrate; Link & Paste CRUD
├── slug/
│ └── slug.go # Base-36 slug generation and validation
└── server/
├── server.go # HTTP mux registration; security headers middleware
├── handlers.go # All request handlers; template rendering helpers
├── middleware.go # requireAuth, requireCSRF, rateLimiter, sessionStore, clientIP
├── static/
│ └── style.css # Custom styles on top of Pico CSS
└── templates/
├── index.html # Public home: shorten form + QR result
├── admin_login.html # Login form (dark, centered card)
├── admin.html # Admin dashboard: stats bar, tiles, links tables
├── admin_edit.html # Edit a single link
├── admin_bin.html # Pastes list with format/token badges
├── admin_bin_edit.html # Create / edit a paste
├── bin_view.html # Public paste viewer (GitHub Gist style)
└── 404.html # Not found page
Dependencies
| Package | Purpose |
|---|---|
github.com/BurntSushi/toml |
TOML config parsing |
golang.org/x/crypto/bcrypt |
Admin password hashing |
modernc.org/sqlite |
Pure-Go SQLite driver (no CGo required) |
github.com/yuin/goldmark |
Markdown rendering (GFM + tables) |
rsc.io/qr |
Server-side QR code generation (SVG) |
All other entries in go.sum are transitive dependencies of the above.
Getting Started
Prerequisites
- Go 1.22 or later
- No CGo, no external C libraries, no system SQLite needed
Windows note: If Go is not in your bash
PATH, prefix every command:export PATH="/c/Program Files/Go/bin:$PATH"
1. Clone and install dependencies
git clone <repo-url>
cd url
go mod download
2. Configure
Edit config.toml:
[server]
port = 8888
base_url = "http://localhost:8888" # Override by Host header at runtime
read_timeout = "5s"
write_timeout = "10s"
[admin]
username = "admin"
password_hash = "$2a$10$..." # See step 3 below
session_hours = 24
[database]
path = "./data/urls.db"
[slugs]
length = 3 # Auto-generated slug length (characters)
3. Set your admin password
./urlshort --hash-password "your-secure-password"
# or via make:
make hash
Copy the printed bcrypt hash into config.toml under admin.password_hash.
4. Build and run
# Windows
make build
./urlshort.exe
# Linux / macOS
make build-linux
./urlshort
# Raspberry Pi Zero (ARMv5)
make build-arm
# Copy urlshort-arm to the Pi, then run it there
The server starts on http://localhost:8888 (or whatever port you set).
Makefile Targets
| Target | Description |
|---|---|
make build |
Build urlshort.exe for Windows (stripped binary) |
make build-linux |
Build urlshort for Linux x86-64 |
make build-arm |
Cross-compile urlshort-arm for Raspberry Pi Zero (ARMv5) |
make run |
Build then immediately run on Windows |
make clean |
Remove all compiled binaries |
make hash |
Interactively hash a password for config.toml |
Deploying to Raspberry Pi Zero
# On your dev machine — cross-compile for ARMv5 (Pi Zero)
make build-arm
# Copy binary, config, and deploy scripts to the Pi
scp urlshort-arm [email protected]:~/urlshort
scp config.toml [email protected]:~/config.toml
scp -r deploy/ [email protected]:~/deploy/
The binary is fully self-contained — no Go runtime, no system SQLite, no shared libraries required.
Install as a system service
The deploy/ directory contains an install script and service files compatible with Ubuntu/Debian (both modern systemd and older SysV init systems):
# On the Pi (or any Ubuntu/Debian host):
chmod +x urlshort
sudo ./deploy/install.sh
The script will:
- Create a dedicated
urlshortsystem user - Install the binary to
/opt/urlshort/ - Install the config to
/etc/urlshort/config.toml - Create
/var/lib/urlshort/for the database - Register and enable the service (systemd or SysV, auto-detected)
After install, set your admin password hash in the config:
/opt/urlshort/urlshort -hash-password "your-secure-password"
# Paste the output into /etc/urlshort/config.toml → admin.password_hash
sudo systemctl start urlshort
Service management:
sudo systemctl status urlshort
sudo systemctl restart urlshort
sudo journalctl -u urlshort -f # live logs
Behind a Reverse Proxy — nginx
The app reads Host and X-Forwarded-Proto headers automatically to build correct short URLs and set Secure cookies. No base_url change is needed in config.toml when running behind a proxy.
1. Install nginx
sudo apt update
sudo apt install -y nginx
2. Create a site config
sudo nano /etc/nginx/sites-available/urlshort
Paste the following, replacing short.example.com with your domain:
server {
listen 80;
server_name short.example.com;
location / {
proxy_pass http://127.0.0.1:8888;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_read_timeout 30s;
proxy_send_timeout 30s;
}
}
sudo ln -s /etc/nginx/sites-available/urlshort /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx
At this point the site is reachable over HTTP. Proceed to step 3 to add HTTPS.
3. Add HTTPS with Let's Encrypt (certbot)
sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d short.example.com
Certbot will automatically update the nginx config to add SSL and redirect HTTP → HTTPS. Certificates auto-renew via a systemd timer or cron job that certbot installs.
No public domain? If running on a local network (e.g. Raspberry Pi at home), skip certbot and use a self-signed certificate instead:
sudo openssl req -x509 -nodes -days 3650 -newkey rsa:2048 \ -keyout /etc/ssl/private/urlshort.key \ -out /etc/ssl/certs/urlshort.crt \ -subj "/CN=urlshort"Then reference them manually in the nginx config (
ssl_certificate,ssl_certificate_key).
4. Recommended production nginx config
After certbot runs, your config will look roughly like this. The additions below tighten security headers and enable compression:
server {
listen 80;
server_name short.example.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name short.example.com;
# TLS — managed by certbot
ssl_certificate /etc/letsencrypt/live/short.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/short.example.com/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
# Compression
gzip on;
gzip_types text/css text/html application/javascript;
gzip_min_length 1024;
# Security headers
add_header Strict-Transport-Security "max-age=31536000" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
add_header Referrer-Policy "strict-origin" always;
location / {
proxy_pass http://127.0.0.1:8888;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_read_timeout 30s;
proxy_send_timeout 30s;
proxy_buffering off;
}
}
sudo nginx -t && sudo systemctl reload nginx
5. Update config.toml base_url (optional)
base_url is only used as a fallback when no Host header is present (e.g. direct curl on localhost). When nginx is in front, the Host header is always forwarded, so the generated short links will automatically use your domain. If you want the fallback to also be correct:
[server]
base_url = "https://short.example.com"
Then restart the service: sudo systemctl restart urlshort
Verify everything works
# Confirm redirect (should return 301 to https)
curl -I http://short.example.com/
# Confirm HTTPS proxy is working
curl -I https://short.example.com/
# Check urlshort is running and nginx can reach it
sudo systemctl status urlshort
sudo systemctl status nginx
Cloudflare note
If proxying through Cloudflare, X-Forwarded-For is safe to trust for rate limiting since Cloudflare controls the header. For direct-to-internet deployments without a trusted proxy, clients could spoof X-Forwarded-For to bypass IP rate limits — see "Possible Future Improvements".
URL Routes
| Method | Path | Auth | Description |
|---|---|---|---|
GET |
/ |
Public | Home / shorten form |
POST |
/shorten |
Public | Create short link |
GET |
/{slug} |
Public | Redirect to destination |
GET |
/bin/{name} |
Public | View paste |
GET |
/bin/{name}/{token} |
Public | View token-protected paste |
GET |
/admin/login |
Public | Login form |
POST |
/admin/login |
Public | Submit login |
POST |
/admin/logout |
Admin | Logout (CSRF protected) |
GET |
/admin |
Admin | Dashboard: links + tiles |
GET |
/admin/edit/{id} |
Admin | Edit link form |
POST |
/admin/edit/{id} |
Admin | Save link edit (CSRF) |
POST |
/admin/delete/{id} |
Admin | Delete link (CSRF) |
GET |
/admin/bin |
Admin | Pastes list |
GET |
/admin/bin/new |
Admin | New paste form |
POST |
/admin/bin/new |
Admin | Create paste (CSRF) |
GET |
/admin/bin/edit/{id} |
Admin | Edit paste form |
POST |
/admin/bin/edit/{id} |
Admin | Save paste edit (CSRF) |
POST |
/admin/bin/delete/{id} |
Admin | Delete paste (CSRF) |
GET |
/static/* |
Public | CSS / static assets |
Database Schema
SQLite, WAL mode, single writer, auto-migrated on startup.
CREATE TABLE links (
id INTEGER PRIMARY KEY AUTOINCREMENT,
slug TEXT NOT NULL UNIQUE,
url TEXT NOT NULL,
created_by TEXT NOT NULL DEFAULT 'anonymous', -- 'admin' or 'anonymous'
clicks INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE pastes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE, -- URL slug, e.g. "my-script"
title TEXT NOT NULL DEFAULT '',
content TEXT NOT NULL DEFAULT '',
format TEXT NOT NULL DEFAULT 'markdown', -- 'markdown' | 'text'
token TEXT, -- NULL = public; non-null = token required
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
To reset the database (e.g. during development):
rm -f data/urls.db
# Restart the server — it will recreate the DB automatically
Configuration Reference
[server]
port = 8888 # TCP port to listen on
base_url = "http://localhost:8888" # Fallback base URL (overridden by Host header)
read_timeout = "5s" # HTTP read timeout
write_timeout = "10s" # HTTP write timeout
[admin]
username = "admin" # Admin login username
password_hash = "$2a$10$..." # bcrypt hash — generate with: ./urlshort --hash-password
session_hours = 24 # How long admin sessions last
[database]
path = "./data/urls.db" # Path to SQLite file (directory auto-created)
[slugs]
length = 3 # Length of auto-generated slugs (recommended: 3–6)
Security Notes
- Change the default password. The default hash in
config.tomlis for the passwordadmin. Run./urlshort --hash-passwordimmediately. - CSRF protection uses the double-submit cookie pattern. Every admin POST requires a
csrf_tokenform field matching thecsrfcookie value, compared with constant-time equality. - Sessions are stored in memory. They are lost when the server restarts (acceptable for single-user use). Session IDs are 32 bytes of
crypto/rand. - Paste tokens are 12-character random strings. Token comparison uses
crypto/subtle.ConstantTimeCompareto prevent timing attacks. - Rate limiting is 1 short link per second per IP for anonymous users. The rate limiter table is lazily cleaned up at 10,000 entries.
Development Tips
Rebuild and restart quickly (Windows)
export PATH="/c/Program Files/Go/bin:$PATH"
pkill -f urlshort.exe; sleep 1
go build -o urlshort.exe ./ && ./urlshort.exe &
Check logs
# If started with output redirected:
tail -f /tmp/urlshort.log
Useful one-liners
# Hash a new password
go run . --hash-password "mynewpassword"
# Check what's listening on 8888 (Windows PowerShell)
Get-NetTCPConnection -LocalPort 8888 | Select-Object OwningProcess
# Kill whatever is on port 8888 (Windows PowerShell)
Get-NetTCPConnection -LocalPort 8888 | ForEach-Object { Stop-Process -Id $_.OwningProcess -Force }
Possible Future Improvements
- Configurable trusted-proxy IP list (for safer
X-Forwarded-Forhandling) - Persistent sessions (write to SQLite) so restarts don't log out admin
- Optional expiry date per link
- Bulk delete / bulk import via CSV
- Syntax highlighting for code pastes