Skip to content
Public template

About

Golang Starter for smart build and development

Resources

Stars

0 stars

Watchers

0 watching

Forks

 
 

Repository files navigation

go-starter

Modular Go backend starter — Echo v5 + GORM + JWT, with ready-to-use auth, roles RBAC, health check, and multi-pod load balancing.

Starter template for building production-ready modular Go backends. Ships with a complete authentication system (register, login, JWT access/refresh tokens, Google OAuth, password reset, file upload), granular RBAC roles management, health monitoring, and a high-availability multi-pod Docker setup with Nginx load balancing.


✨ Features

  • Modular monolith — every feature is a self-contained module (modules/<name>/) with domain/entity, domain/repository, domain/service, handler, and dto layers
  • Roles & Granular RBAC (modules/roles) — Full role management, extensible menu permission registry, RequirePermission(menuKey) and RequireSuperAdmin middlewares
  • Multi-Pod Load Balancing — High-availability backend pods (go-starter-pod-1 and go-starter-pod-2) behind an Nginx gateway with dynamic upstream failover (proxy_next_upstream)
  • Health Check Module (modules/health) — GET /api/v1/health with X-Backend-Node header for load balancing verification, database ping, and server uptime
  • Auth Module (modules/auth) — Register, login, logout, JWT access + refresh tokens, change/reset password, email & username availability checks
  • Google OAuth2 login with automatic account creation
  • UUIDv7 Primary Keys — Time-ordered RFC 9562 UUIDv7 IDs for efficient database indexing
  • Security & Network Utilities — Baseline HTTP security headers (nosniff, DENY, strict-origin), and Real IP extractor (CF-Connecting-IP, X-Real-IP, X-Forwarded-For)
  • Standalone Database Migrations — Decoupled ./bin/migrate CLI runner running both SQL files and module schema migrations without app boot collisions
  • In-memory event bus — modules publish events like user.created for loose coupling
  • Swagger docs — auto-generated from handler annotations, served at /api/docs/
  • Graceful shutdown, CORS, request validation, zap logging with rotation

🛠️ Tech Stack

Layer Tech
Language Go 1.25
HTTP Echo v5
ORM GORM (PostgreSQL)
Auth JWT (HS256) — separate access & refresh keys (jwt/v5)
Load Balancer Nginx Alpine (Reverse Proxy & Upstream Failover)
Validation go-playground/validator
Logging zap + lumberjack
Config 100% env-var via godotenv
OAuth Google (golang.org/x/oauth2)
Docs swaggo/swag
Infra Docker + docker compose (migrate, app-1, app-2, load-balancer)

🚀 Getting Started

Prerequisites

  • Go 1.25+
  • PostgreSQL (or Docker)

Installation (Local)

# 1. Clone the repo
git clone <your-repo-url> go-starter
cd go-starter

# 2. Copy and fill in the environment config
cp .env.example .env
#   - set DB_DRIVER=postgres, DB_HOST, DB_PORT, DB_* creds
#   - set JWT_SIGNATURE_KEY and JWT_REFRESH_KEY to random secrets

# 3. Apply database migrations
make migrate-up

# 4. Build & run
go build -o main .
go run main.go

Server starts on :8080 by default. Swagger docs at http://localhost:8080/api/docs/.

Running with Docker (Multi-Pod Load Balancer)

make deploy
# OR:
docker compose build --no-cache && ./deployments/docker/entrypoint.sh

This spins up:

  1. migrate: Applies SQL and module database migrations and exits successfully.
  2. go-starter-pod-1: Backend instance 1 (APP_INSTANCE_ID=go-starter-pod-1).
  3. go-starter-pod-2: Backend instance 2 (APP_INSTANCE_ID=go-starter-pod-2).
  4. go-starter-lb: Nginx load balancer listening on :8080 and round-robining requests across both pods.

Test the load balancer node distribution:

curl -I http://localhost:8080/api/v1/health
# Inspect the X-Backend-Node header alternating between go-starter-pod-1 and go-starter-pod-2

Useful Commands

make build-backend    # go build -o main .
make run-backend      # go run main.go
make test-backend     # go test ./...
make build-migrate    # build bin/migrate CLI
make migrate-up       # apply pending database migrations
make migrate-down     # revert database migrations
make migrate-new      # scaffold new migration (make migrate-new name=add_feature)
make swagger          # regenerate Swagger docs
make deploy           # build & deploy multi-pod stack with load balancer
make docker-down      # stop all services
make docker-logs      # follow container logs

🔌 API Routes

All routes under prefix /api/v1 (configurable via API_VERSION). JWT = requires Authorization: Bearer <access_token>.

Health (/api/v1/health)

Method Path Auth Description
GET /health No Health check returning node instance ID (X-Backend-Node), database status, and uptime

Roles & RBAC (/api/v1/roles)

Method Path Auth Description
GET /roles/menu-registry Super Admin Get all standard menu permission keys
GET /roles Super Admin List all roles and permissions
GET /roles/:id Super Admin Get role details by ID
POST /roles Super Admin Create new custom role
PUT /roles/:id Super Admin Update role name, description, and permissions
DELETE /roles/:id Super Admin Delete custom role (system roles cannot be deleted)

Auth (/api/v1/auth)

Method Path Auth Description
POST /auth/register No Register a new user (returns access + refresh tokens)
POST /auth/login No Login with email + password
POST /auth/refresh No Exchange refresh token for new access token
GET /auth/check-email No Check email availability
GET /auth/check-username No Check username availability
POST /auth/forgot-password No Send password reset email
GET /auth/verify-reset-token No Verify a reset token
POST /auth/reset-password No Reset password with token
GET /auth/google/login No Redirect to Google OAuth consent
GET /auth/google/callback No Google OAuth callback
GET /auth/profile JWT Get own profile
PUT /auth/profile JWT Update own profile
PUT /auth/username JWT Set username (first-time Google users)
POST /auth/change-password JWT Change password
POST /auth/logout JWT Logout
POST /auth/upload JWT Upload a file (stored in public/uploads)

Users (/api/v1)

Method Path Auth Description
GET /u/:username No Public user profile by username
GET /users JWT List all users
GET /users/:id JWT Get user by ID
POST /users JWT Create user
PUT /users/:id JWT Update user
DELETE /users/:id JWT Delete user

🏗️ Architecture & Modules

Every module implements internal/app/module.go:

type Module interface {
    Name() string
    Initialize(db *gorm.DB, logger *logger.Logger, event *bus.EventBus) error
    RegisterRoutes(e *echo.Echo, group string)
    Migrations() error
    Logger() *logger.Logger
}
modules/<name>/
├── domain/
│   ├── entity/        # GORM models with UUIDv7 BeforeCreate hooks
│   ├── repository/    # interface + GORM implementation
│   └── service/       # domain business logic
├── handler/           # Echo handlers + route registration
├── dto/
│   ├── request/
│   └── response/
└── module.go          # module wiring (repo → service → handler)

About

Golang Starter for smart build and development

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages