Skip to content
/ go-web-server Public template

A production-ready template for modern web applications using The Modern Go Stack - a cohesive technology stack for building high-performance, maintainable applications. Creates single, self-contained binaries with zero external dependencies.

License

Notifications You must be signed in to change notification settings

dunamismax/go-web-server

Repository files navigation

Go Web Server Template Logo

Typing SVG

Go Version Echo Framework Templ HTMX Pico.css SQLC PostgreSQL pgx PostgreSQL Driver Go slog Viper Goose Mage Air MIT License


Live Demo

View Live Demo → - Self-hosted production deployment showcasing the complete Modern Go Stack in action.


About

A production-ready template for modern web applications using The Modern Go Stack - a cohesive technology stack for building high-performance, maintainable applications. Creates single, self-contained binaries with zero external dependencies.

Key Features:

  • Echo v4 + Templ + HTMX: High-performance web framework with type-safe templates and dynamic UX
  • SQLC + PostgreSQL + pgx Driver: Type-safe database operations with high performance and connection pooling
  • JWT Authentication: Secure token-based authentication with configurable expiration and cookie support
  • Prometheus Metrics: Comprehensive observability and performance monitoring with custom business metrics
  • Enterprise Security: CSRF protection, input sanitization, XSS/SQL injection prevention, structured error handling
  • Mage Build System: Go-based automation with comprehensive quality checks and vulnerability scanning
  • Production Ready: Rate limiting, CORS, security headers, graceful shutdown, and embedded static assets
  • Developer Experience: Hot reload with Air, database migrations with Goose, multi-source config with Viper

Tech Stack

Layer Technology Purpose
Language Go 1.24+ Latest performance & language features
Framework Echo v4 High-performance web framework
Templates Templ Type-safe Go HTML components
Frontend HTMX Dynamic interactions with smooth UX
CSS Pico.css v2 Semantic CSS with dark/light themes
Authentication JWT + bcrypt Secure token-based auth with password hashing
Logging slog Structured logging with JSON output
Database PostgreSQL Enterprise-grade relational database
Queries SQLC Generate type-safe Go from SQL
Validation go-playground/validator Comprehensive input validation
Metrics Prometheus Performance monitoring & observability
DB Driver pgx v5 High-performance PostgreSQL driver with pooling
Assets Go Embed Single binary with embedded resources
Config Viper Multi-source configuration management
Migrations Goose Database migration management
Build Mage Go-based build automation
Hot Reload Air Development server with live reload

Quick Start

Ubuntu Production Deployment (Recommended)

# Clone repository
git clone https://github.com/dunamismax/go-web-server.git
cd go-web-server

# Install PostgreSQL
sudo apt update
sudo apt install postgresql postgresql-contrib

# Create database and user
sudo -u postgres createdb gowebserver
sudo -u postgres createuser -P gowebserver  # Set password when prompted

# Create your environment file
cp .env.example .env
# Edit .env with your database credentials (DATABASE_USER, DATABASE_PASSWORD, etc.)

# Install Go dependencies and build
mage setup
mage build

# Run database migrations
mage migrate

# Server binary available at: bin/server

Requirements: Ubuntu 20.04+, PostgreSQL, Go 1.24+

Local Development

# Clone and setup
git clone https://github.com/dunamismax/go-web-server.git
cd go-web-server
go mod tidy

# Create your environment file
cp .env.example .env
# Edit .env with your database credentials (DATABASE_USER, DATABASE_PASSWORD, etc.)

# Install development tools and dependencies
mage setup

# Ensure PostgreSQL is running locally
sudo systemctl start postgresql
sudo systemctl enable postgresql

# Start development server with hot reload
mage dev

# Server starts at http://localhost:8080

Requirements:

  • Go 1.24+
  • Mage build tool (go install github.com/magefile/mage@latest)
  • PostgreSQL database (local installation)

Note: First run of mage setup installs all development tools automatically.

Documentation

Complete Documentation - Comprehensive guides for development, deployment, security, and architecture.

Guide Description
Development Guide Local setup, hot reload, database management, and daily workflow
API Reference HTTP endpoints, HTMX integration, and CSRF protection
Architecture System design, components, and technology decisions
Security Guide CSRF, sanitization, headers, rate limiting, and monitoring
Deployment Guide Traditional production deployment and configuration

Gopher Mage

Mage Commands

Run mage help to see all available commands and their aliases.

Development:

mage setup (s)        # Install tools and dependencies
mage generate (g)     # Generate sqlc and templ code
mage dev (d)          # Start development server with hot reload
mage run (r)          # Build and run server
mage build (b)        # Build production binary

Database:

mage migrate (m)      # Run database migrations up
mage migrateDown      # Roll back last migration
mage migrateStatus    # Show migration status

Quality & Production:

mage fmt (f)          # Format code with goimports and tidy modules
mage vet (v)          # Run go vet static analysis
mage lint (l)         # Run golangci-lint comprehensive linting
mage vulncheck (vc)   # Check for security vulnerabilities
mage quality (q)      # Run all quality checks
mage ci               # Complete CI pipeline
mage clean (c)        # Clean build artifacts

Observability & Monitoring:

# Enable Prometheus metrics (via environment variables)
FEATURES_ENABLE_METRICS=true mage run
# Then access metrics at: http://localhost:8080/metrics

# Enhanced health checks with database connectivity
curl http://localhost:8080/health

# Test JWT authentication endpoints
curl -X POST http://localhost:8080/auth/register \
  -H "Content-Type: application/json" \
  -d '{"email":"[email protected]","name":"Test User","password":"StrongPass123"}'

curl -X POST http://localhost:8080/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email":"[email protected]","password":"StrongPass123"}'

# Note: Demo mode currently bypasses password validation for existing users.
# For production, implement proper password hashing and validation in auth handlers.

Live Demo

Web Application (localhost:8080)

Interactive user management application demonstrating:

  • JWT Authentication: Login/register system with secure token-based auth
  • CRUD Operations: Type-safe database queries with CSRF protection
  • Real-time Updates: HTMX interactions with smooth page transitions
  • Responsive Design: Automatic dark/light theme switching with Pico.css
  • Enterprise Security: Input sanitization, XSS/SQL injection prevention, and structured error handling

Go Web Server Screenshot

Easter Egg: The default user database comes pre-populated with Robert Griesemer, Rob Pike, and Ken Thompson - the three brilliant minds who created the Go programming language at Google starting in 2007. A small tribute to the creators of the language that powers this entire stack!

Project Structure

go-web-server/
├── cmd/web/              # Application entry point with main.go
├── docs/                 # Complete documentation
├── internal/
│   ├── config/           # Viper configuration management
│   ├── handler/          # HTTP handlers (auth, home, user, routes)
│   ├── middleware/       # Security, auth, CSRF, validation, error handling, metrics
│   ├── store/            # Database layer with SQLC (models, queries, migrations)
│   │   └── migrations/   # Goose database migrations
│   ├── ui/               # Static assets (embedded CSS, JS, favicon)
│   └── view/             # Templ templates and components
├── scripts/              # Deployment scripts and systemd service
├── bin/                  # Compiled binaries
├── tmp/                  # Development hot reload directory  
├── magefile.go          # Mage build automation with comprehensive commands
├── .golangci.yml        # Linter configuration
├── sqlc.yaml            # SQLC configuration
├── go.mod/go.sum        # Go module dependencies
└── .env.example         # Environment configuration template

Go Gopher

Ubuntu SystemD Deployment

# Build optimized binary for production deployment
mage build  # Creates optimized binary in bin/server (~15MB)

# Create systemd service file
sudo cp scripts/gowebserver.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable gowebserver
sudo systemctl start gowebserver

The binary includes embedded Pico.css, HTMX, and Templ templates. Single binary deployment with local PostgreSQL backend. Perfect for traditional Ubuntu servers behind Caddy reverse proxy with Cloudflare DNS.

Key Features Demonstrated

Modern Web Stack:

  • Echo framework with comprehensive middleware stack (recovery, CORS, rate limiting, timeouts)
  • JWT authentication with secure cookie handling and configurable expiration
  • Type-safe Templ templates with reusable components and embedded static assets
  • HTMX dynamic interactions with smooth page transitions and custom events
  • Pico.css semantic styling with automatic dark/light themes
  • SQLC type-safe database queries with high-performance pgx driver and connection pooling
  • Structured logging with slog and configurable JSON/text output
  • Prometheus metrics for observability with HTTP, database, and business metrics

Developer Experience:

  • Hot reloading with Air for rapid development
  • Comprehensive error handling with custom error types and structured logging
  • Static analysis suite (golangci-lint, govulncheck, go vet)
  • Mage build automation with goimports, templ formatting, and vulnerability scanning
  • Single-command CI pipeline with quality checks and linting
  • Environment-based configuration with sensible defaults

Production Ready:

  • Enterprise security with CSRF protection, input sanitization, and XSS/SQL injection prevention
  • JWT authentication with bcrypt password hashing and secure cookie management
  • Structured error handling with request tracing, correlation IDs, and monitoring
  • Multi-source configuration with Viper supporting JSON, YAML, ENV, and .env files
  • Database migrations with Goose, connection pooling, and graceful shutdown
  • Single binary deployment (~15MB) with embedded assets (CSS, JS, templates)
  • Comprehensive middleware stack with rate limiting, CORS, security headers, and timeouts
  • Prometheus metrics integration with custom business and performance metrics

Buy Me A Coffee

Twitter Bluesky Reddit Discord Signal

License

This project is licensed under the MIT License - see the LICENSE file for details.


The Modern Go Stack
Echo • Templ • HTMX • JWT • SQLC • PostgreSQL • pgx • Prometheus • slog • Viper • Goose • Mage • Air

Gopher Running and Jumping


"The "Modern Go Stack" is a powerful and elegant solution that aligns beautifully with Go's core principles. It is an excellent starting point for many new projects, and any decision to deviate from it should be driven by specific, demanding requirements." - Me


About

A production-ready template for modern web applications using The Modern Go Stack - a cohesive technology stack for building high-performance, maintainable applications. Creates single, self-contained binaries with zero external dependencies.

Topics

Resources

License

Security policy

Stars

Watchers

Forks