Skip to main content
The API template uses a feature-based architecture. β€œFeature-based” means your code is organized by what it does (users, products, orders) rather than by type (models, controllers, views). This makes it easier to find related code and work on one feature without affecting others.

Directory Layout

The cmd/ Directory

Contains the entry point(s) for your application.

cmd/api/main.go

What it does:
  1. Loads configuration
  2. Creates the application
  3. Starts the HTTP server
Why separate from app/?
  • Keeps main() minimal
  • Makes it easy to add more commands (workers, migrations)
  • Application logic is testable without main()

The app/ Directory

Contains application setup and configuration.

app/api/app.go

What it does:
  • Defines the App struct that holds configuration and router
  • Provides a New() constructor that sets everything up
  • Exposes a Listen() method to start the server
Key concepts:

app/api/config.go

What it does:
  • Defines configuration structure
  • Loads values from environment variables
  • Provides sensible defaults
Adding more config:

app/api/routes.go

What it does:
  • Registers all routes in one place
  • Imports handlers from feature packages
  • Makes route structure visible at a glance
Adding a new route:

The feature/ Directory

Contains your business logic, organized by domain.

feature/health/http.go

Pattern: Factory function that returns a handler. Why this pattern?
  • Handlers can accept dependencies (database, logger)
  • Clean separation between setup and execution
  • Easy to test

feature/hello/http.go

Simple text response handler.

feature/echo/http.go

What it does:
  • Reads JSON from request body
  • Returns the same JSON back
  • Useful for testing

feature/users/http.go

What it shows:
  • Type definitions live with their handlers
  • Mock data for the example (replace with database)
  • Clean API boundary

Adding a New Feature

Let’s add a products feature:

1. Create the Package

2. Create the Handler

Create feature/products/http.go:

3. Register Routes

Edit app/api/routes.go:

4. Test It

File Naming Conventions

Best Practices

Keep Handlers Thin

Use Dependency Injection

Next Steps

Tutorial

Build a complete API from scratch

Contract Template

See an even more structured approach