Go Shortener is a simple URL shortening service built with Go. It allows you to shorten long URLs, redirect users to the original URLs, and optionally collect click statistics. This project is intended for both learning purposes and practical use.
- URL Shortening: Generate short links from long URLs.
- Redirection: Automatically redirect from a short URL to the original long URL.
- REST API: Easily integrate with other services via a well-defined API.
- Language: Go
- Clone the Repository:
git clone https://github.com/vlxdisluv/shortener.git
- Navigate to the Project Directory:
cd shortener - Install Dependencies:
go mod tidy
- A sample environment file is provided as
.env.example. - Copy it to
.envand adjust values as needed:cp .env.example .env
- The application autoloads
.envat startup.
Supported environment variables:
SERVER_ADDR— HTTP server address (e.g.,localhost:8080).BASE_URL— Base URL for generated short links (falls back tohttp://<SERVER_ADDR>).LOG_LEVEL— Logging level (e.g.,info).ENVIRONMENT— Environment name (e.g.,development,production).FILE_STORAGE_PATH— Path to JSON file used for file-based storage (default:/tmp/short-url-db.json).DATABASE_DSN— Postgres connection string (enables Postgres storage when set).
- By default, the service uses a file-based storage.
- To use Postgres instead of the file storage, provide a Postgres DSN via either:
- Environment: set
DATABASE_DSNin.env(or the environment), or - CLI flag:
-d "<postgres_dsn>".
- Environment: set
- If neither the flag nor the env var is provided, the file storage will be used.
A Docker Compose configuration is included to run Postgres locally.
-
Start Postgres and run migrations:
docker compose up -d
This will start a Postgres 15 container and apply migrations.
-
To connect the application to this Postgres instance, set the
DATABASE_DSNor use the-dflag as described in the Running section below.
- File storage (default):
go run cmd/shortener/main.go
- Postgres via env (
.envor shell):export DATABASE_DSN="postgres://shortener:shortener@localhost:5432/postgres?sslmode=disable" go run cmd/shortener/main.go
- Postgres via flag:
go run cmd/shortener/main.go -d "postgres://shortener:shortener@localhost:5432/postgres?sslmode=disable"
To run the automated tests, use:
go test ./...