Skip to content

PlatformStackPulse/go-template

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

18 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Go Template

Go Version License: MIT CI Status codecov DevContainer

Slim, Production-Ready Go Template
Enterprise CI/CD, DevSecOps, clean architecture. Optimized for CLI tools and API servers.


🎯 Overview

A minimal, reusable GitHub template for building production-ready Go applications. Supports both CLI single-binary projects and API servers with zero bloat.

What you get:

  • βœ… Clean architecture (Domain/Usecase/Adapter layers)
  • βœ… CLI foundation (Cobra framework, ready for commands)
  • βœ… Structured logging (slog)
  • βœ… Configuration management
  • βœ… Comprehensive testing (unit, integration)
  • βœ… DevSecOps (gosec, govulncheck, CodeQL)
  • βœ… GitHub Actions CI/CD (linting, testing, releases)
  • βœ… Docker & multi-platform builds
  • βœ… DevContainer with pre-configured tools
  • βœ… Kubernetes & Terraform examples

What you don't get (keep it slim!):

  • No bloated feature flag systems
  • No unused HTTP/health endpoints (add only if needed)
  • No example commands cluttering production code (we include one example to remove)
  • No over-engineered abstractions

πŸš€ Quick Start

Using as GitHub Template

# Create a new repo from this template
gh repo create my-app --template go-template

# Setup
cd my-app
make dev-setup

# Build & run
make build
./bin/go-template hello --name "World"

Example: Add Your First Command

The template includes an example command in internal/cli/hello.go (via NewExampleCommand). Replace it with your own:

1. Create your command:

// internal/cli/mycommand.go
package cli

import (
	"github.com/spf13/cobra"
	"github.com/PlatformStackPulse/go-template/internal/logger"
)

func NewMyCommand(log *logger.Logger) *cobra.Command {
	return &cobra.Command{
		Use:        "mycommand",
		Short:      "What my command does",
		Long:       "Detailed description of what my command does",
		RunE: func(cmd *cobra.Command, args []string) error {
			log.Info("Running mycommand")
			// Your logic here
			return nil
		},
	}
}

2. Register in main.go:

// cmd/app/main.go
cmd.AddCommand(cli.NewMyCommand(log))

3. Remove the example command:

rm internal/cli/hello.go
# Update cmd/app/main.go - remove the cli.NewExampleCommand line

πŸ“ Lean Project Structure

go-template/
β”œβ”€β”€ cmd/app/
β”‚   └── main.go                 # Entry point (minimal, ~30 lines)
β”œβ”€β”€ internal/                   # Private packages
β”‚   β”œβ”€β”€ cli/                    # Cobra commands
β”‚   β”‚   β”œβ”€β”€ root.go            # Root command
β”‚   β”‚   └── hello.go           # Example command (remove/rename)
β”‚   β”œβ”€β”€ config/                # Configuration loading
β”‚   β”œβ”€β”€ domain/                # Domain entities
β”‚   β”œβ”€β”€ logger/                # Structured logging (slog)
β”‚   β”œβ”€β”€ usecase/               # Business logic
β”‚   └── adapter/               # External integrations (add as needed)
β”œβ”€β”€ pkg/
β”‚   └── version/               # Version info (injected at build)
β”œβ”€β”€ test/
β”‚   β”œβ”€β”€ unit/                  # Unit tests
β”‚   └── integration/           # Integration tests (if needed)
β”œβ”€β”€ deploy/
β”‚   β”œβ”€β”€ kubernetes/            # K8s manifests (optional)
β”‚   └── terraform/             # IaC (optional)
β”œβ”€β”€ Makefile                   # Core build targets
β”œβ”€β”€ Dockerfile                 # Multi-stage build
β”œβ”€β”€ go.mod / go.sum            # Dependencies
└── .github/workflows/         # GitHub Actions (6 workflows)

🎯 Two Modes: CLI vs API

Mode 1: CLI (Single Binary)

Your main.go stays slim:

func main() {
	cfg := config.Load()
	log := logger.NewLogger(cfg.Debug)
	cmd := cli.NewRootCommand(log)
	cmd.Version = version.Version
	
	if err := cmd.ExecuteContext(context.Background()); err != nil {
		os.Exit(1)
	}
}

Add your commands to internal/cli/ and register them in cmd/app/main.go.

Mode 2: API Server

Extend main.go with HTTP:

func main() {
	cfg := config.Load()
	log := logger.NewLogger(cfg.Debug)
	
	// Create HTTP server
	srv := &http.Server{
		Addr:    ":8080",
		Handler: setupRoutes(log),
	}
	
	// Run with graceful shutdown
	// (add your HTTP handler logic)
}

Optional: Add files as needed:

  • internal/http/server.go β€” HTTP server setup
  • internal/http/handlers.go β€” Route handlers
  • pkg/health/ β€” Health check endpoints

πŸ“ Architecture

Clean layers with clear separation:

CLI/HTTP Layer (User interaction)
         ↓
Usecases (Business logic)
         ↓
Domain (Entities, rules)
         ↓
Adapters (External services)

Each layer is independent and testable.


πŸͺ΅ Design Philosophy

  • Slim β€” Only essential structure, no bloat
  • Extensible β€” Easy to add features without refactoring
  • Example-first β€” Rename/remove example command, add yours
  • Test-friendly β€” Proper layering makes testing straightforward
  • Single responsibility β€” Each package does ONE thing well

βš™οΈ Common Tasks

make dev-setup       # Install tools
make build           # Build binary
make test            # Run tests
make coverage        # Coverage report
make fmt             # Format code
make lint            # Lint check
make security        # Security scan
make docker-build    # Build Docker image

See Makefile for all targets.


πŸ”„ Customization Checklist

When using this template:

  • Update go.mod module name
  • Rename go-template binary in Makefile and README.md
  • Remove/rename internal/cli/hello.go example command
  • Update repository references in documentation
  • Add your commands to internal/cli/
  • Update tests in test/unit/

πŸ“¦ Deployment

Build for Production

make build                # Build locally
make release             # Build all platforms (macOS/Linux/Windows)
make docker-build        # Build Docker image

Docker

# Already configured in Dockerfile (multi-stage build)
docker build -t my-app .
docker run my-app hello --name "Docker"

Kubernetes (Optional Example)

kubectl apply -f deploy/kubernetes/

See deploy/kubernetes/ for manifests.

Terraform (Optional Example)

cd deploy/terraform
terraform init
terraform plan -var-file=terraform.dev.tfvars

πŸ§ͺ Testing

# All tests
make test

# With coverage
make coverage

# Specific package
go test ./internal/usecase/...

# Race detection
go test -race ./...

πŸ” Security

  • Integrated security scanning (gosec, govulncheck, CodeQL)
  • Vulnerability notifications via Dependabot
  • Branch protection on main
  • Commit signing support

See SECURITY.md for details.


πŸ“š Documentation


πŸ“„ License

MIT License β€” See LICENSE


πŸŽ“ Learn More


Ready to build? Fork this template and start coding! πŸš€

Design Patterns Included

  • Command Pattern β€” Cobra commands
  • Mediator Pattern β€” Feature manager
  • Orchestrator Pattern β€” Usecase layer
  • Dependency Injection β€” Idiomatic Go

πŸ›  Available Commands

Makefile Targets

make help              # Show all available targets
make build             # Build the application
make run               # Build and run
make test              # Run all tests with coverage
make test-unit         # Run unit tests only
make test-integration  # Run integration tests only
make coverage          # Generate coverage report
make clean             # Remove build artifacts
make install           # Install dependencies
make lint              # Run linters
make fmt               # Format code
make vet               # Run go vet
make security          # Run security checks
make sec-update        # Check for security updates
make dev-setup         # Setup development environment
make changelog         # Regenerate CHANGELOG.md from commits
make changelog-check   # Verify CHANGELOG.md is current
make watch             # Watch for changes (air)
make version           # Show version info
make all               # Run all tasks

CLI Commands

./bin/go-template --help
./bin/go-template hello                    # Print "Hello, World!"
./bin/go-template hello --name Alice       # Print "Hello, Alice!"
./bin/go-template version                  # Show version information

πŸ§ͺ Testing

Running Tests

# All tests with coverage
make test

# Specific test suite
make test-unit
make test-integration

# Generate HTML coverage report
make coverage

# Run with race detector
go test -race ./...

Test Coverage

  • Minimum threshold: 70%
  • Enforced in CI: Yes
  • Table-driven tests: Domain and usecase layers
  • Mock patterns: Via interfaces

πŸ” Security & Quality

Integrated Security Tools

Tool Purpose Status
golangci-lint Code quality & style βœ… CI/CD
gosec Security issues βœ… CI/CD
govulncheck Dependency vulnerabilities βœ… CI/CD
CodeQL Static analysis βœ… CI/CD
Dependabot Dependency updates βœ… Automated

Security Checks

# Run all security scans
make security

# Check for vulnerabilities
make sec-update

# Manual gosec scan
gosec ./...

# Manual govulncheck
govulncheck ./...

πŸ“¦ Versioning & Releases

Semantic Versioning

This project follows Semantic Versioning:

MAJOR.MINOR.PATCH
  ↑      ↑      ↑
  β”‚      β”‚      └─ Bug fixes
  β”‚      └────────── New features (backward compatible)
  └───────────────── Breaking changes

Conventional Commits

Commit messages must follow the Conventional Commits specification:

<type>(<scope>): <description>

<body>

<footer>

Types:

  • feat β€” New feature
  • fix β€” Bug fix
  • docs β€” Documentation
  • style β€” Code style
  • refactor β€” Code refactoring
  • perf β€” Performance improvement
  • test β€” Test additions/updates
  • chore β€” Build, dependencies, etc.

Examples:

feat: add hello command with name parameter
fix: resolve panic in logger initialization
docs: update README with quick start guide
chore: upgrade Go from 1.21 to 1.22

Automated Release Process

  1. Create and push tag:

    git tag v1.2.3
    git push origin v1.2.3
  2. Release workflow triggers:

    • Multi-platform builds
    • GitHub Release creation
    • Docker image push
    • SBOM generation
  3. Artifacts available at: https://github.com/PlatformStackPulse/my-app/releases/tag/v1.2.3

Changelog Strategy

  • CHANGELOG.md is generated from Conventional Commits using git-chglog.
  • On merges/pushes to main, .github/workflows/changelog.yml updates and commits CHANGELOG.md automatically.
  • Maintainers can regenerate locally with:
make changelog

🌟 Feature Flags

Quick Example

fm := feature.NewManager()

if fm.IsEnabled(feature.FeatureHello) {
    fmt.Println("Feature is enabled!")
}

Define Flags

Edit internal/feature/flags.go:

const (
    FeatureNewAPI    Flag = "feature_new_api"
    FeatureMetrics   Flag = "feature_metrics"
)

Enable Flags

# Environment variable format
export FEATURE_FLAGS="feature_new_api=true,feature_metrics=false"
./bin/go-template hello

Future Extensions

  • Config file support (YAML/JSON)
  • Remote flag service integration
  • Gradual rollout (percentage)
  • User-based targeting
  • A/B testing support

🐳 Docker

Build Image

# Build locally
docker build -t go-template:latest .

# Run container
docker run --rm go-template:latest hello

# Run with feature flags
docker run --rm \
  -e FEATURE_FLAGS="feature_hello=true" \
  go-template:latest hello

Docker Compose

# Development
docker-compose up dev

# Run tests
docker-compose run test

# Run linter
docker-compose run lint

πŸš€ CI/CD Pipelines

GitHub Actions Workflows

1. CI Pipeline (.github/workflows/ci.yml)

Runs on every push and PR:

  • Code linting (golangci-lint)
  • Format verification
  • Unit & integration tests
  • Coverage enforcement (β‰₯70%)
  • Security scans (gosec, CodeQL)
  • PR commit message validation
  • Multi-version Go testing (1.21, 1.22)

2. Release Pipeline (.github/workflows/release.yml)

Triggers on version tags (v*.*.*):

  • Multi-platform builds (Linux, macOS, Windows)
  • Checksum generation
  • GitHub Release creation with artifacts
  • Docker image build and push
  • SBOM generation

3. Dependency Management (.github/workflows/dependencies.yml)

Weekly automated tasks:

  • Dependency updates
  • Security vulnerability scans
  • Automated PR creation

4. CodeQL Analysis (.github/workflows/codeql.yml)

Runs code scanning on pushes/PRs to main and on a weekly schedule.

5. Changelog Update (.github/workflows/changelog.yml)

Updates CHANGELOG.md from Conventional Commits on pushes to main.


πŸ“š Infrastructure Templates

Kubernetes

Deploy to Kubernetes:

kubectl apply -f deploy/kubernetes/

# Check deployment
kubectl get pods -l app=go-template

Terraform

Deploy to AWS Lambda:

cd deploy/terraform

terraform init
terraform plan -var-file=terraform.dev.tfvars
terraform apply -var-file=terraform.dev.tfvars

πŸ“– Configuration

Environment Variables

Variable Description Default
DEBUG Enable debug logging false
APP_NAME Application name go-template
APP_VERSION Application version dev
FEATURE_FLAGS Enabled feature flags ""

Example .env

DEBUG=true
APP_NAME=my-app
APP_VERSION=v1.0.0
FEATURE_FLAGS=feature_hello=true,feature_metrics=true

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/awesome-feature
  3. Commit with conventional format: git commit -m "feat: add awesome feature"
  4. Push to branch: git push origin feature/awesome-feature
  5. Open a Pull Request

PR Requirements

  • βœ… Must follow Conventional Commits
  • βœ… Tests passing (coverage β‰₯ 70%)
  • βœ… Code linting passing
  • βœ… No security warnings
  • βœ… Documentation updated

πŸ“‹ Checklist for New Projects

When using this template:

  • Update go.mod module path
  • Update module path in code imports
  • Create .github/CODEOWNERS file
  • Update README with project-specific info
  • Configure branch protection rules
  • Setup Dependabot alerts
  • Update repository description
  • Add repository topics
  • Customize GitHub Actions (if needed)
  • Update Terraform variables for your environment

πŸ“œ License

This project is licensed under the MIT License β€” see LICENSE file for details.


πŸ™ Acknowledgments

Built with best practices from:


πŸ“ž Support


Built with ❀️ for platform engineers and Go developers

About

No description, website, or topics provided.

Resources

License

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors