Skip to content
CAI
Software that uses CAICheck a score

diegoclair/go_boilerplate

65.7

Adequate · 6 October 2026

3.8k

lines of production code

Go

primary language

4

measurements over time

CAI band scale
CAI trend line
CAI lens gauges

What this system is

This system is a Go-based REST API service for managing user accounts, authentication, and financial transfers, built upon a Clean Architecture and Domain-Driven Design structure. It provides secure user management features including PASETO-based authentication with login lockout, account balance operations, and transfer processing, backed by a PostgreSQL database and Redis cache. The platform supports observability through Prometheus and Jaeger, and ensures data integrity with structured error handling and automated Swagger documentation.

How it got here

2021 — Clean Architecture migration and PostgreSQL transition

22 changes.

The project underwent a major architectural overhaul to adopt Clean Architecture and Domain-Driven Design, restructuring the codebase into distinct domain, application, and infrastructure layers. This period involved migrating the database backend from MySQL to PostgreSQL, replacing JWT authentication with PASETO tokens, and integrating Redis for session management and rate limiting. Legacy components, including old routing logic, view models, and utility functions, were removed to support the new structure and enhanced security practices.

2022–2024 — Infrastructure and security foundation

12 changes.

This period focused on establishing core infrastructure components, including a Redis-backed cache, centralized configuration management, and graceful shutdown handling. Security was strengthened by adopting Argon2id for password hashing and implementing structured logging with context enrichment. The work also standardized development practices through database migration tooling, typed authentication contexts, and comprehensive mock generation for testing.

2025–2026 — PostgreSQL migration and REST API restructuring

10 changes.

The project migrated its data layer from MySQL to PostgreSQL and restructured the internal architecture into distinct domain, application, and transport layers. This period focused on implementing a new REST API using Echo v5 with goswag documentation, hardening security through explicit validation and token handling, and establishing robust error codes and service contracts.

Features

Add Redis-based cache infrastructure with integration tests

The infra/cache package now provides a Redis-backed caching layer, introducing a CacheManager that supports storing and retrieving strings, integers, bytes, and JSON-serialized structs with configurable expiration times. It includes a specialized IncrBy method for atomic counters that automatically renews the TTL to prevent expiration during active use. To support reliable testing, the package integrates testcontainers to spin up a Redis 8.10.1-alpine instance for integration tests and uses gomock for unit testing the cache interface.

infra/cache · high confidence

Added PostgreSQL database migration support

The application now supports PostgreSQL as a database backend, introducing a new migration module in the \migrator/postgres\ directory. This includes a Go implementation using the \goose\ library to apply schema changes, along with initial SQL migration scripts that create tables for accounts, transfers, and sessions. A corresponding unit test verifies error handling for nil database pools, while integration testing is handled separately via testcontainers.

migrator · high confidence

Added random data generation utilities

Introduced a new \util/random\ package providing helper functions to generate random test data, including random CPFs (via the \go-cpf\ library), random names (6 characters), random passwords (8 characters), and generic random strings of specified lengths. Unit tests were added to verify the output length of these generation functions.

util/random · high confidence

Initial Swagger documentation generation setup

Added goswag configuration files to enable automatic Swagger documentation generation for the Go Boilerplate API. The setup includes route definitions for authentication (login, logout, refresh token), account management, transfers, and a ping endpoint, along with a main entry point that initializes the REST server and triggers Swagger generation.

goswag · high confidence

Introduce REST view models for account, auth, transfer, and pagination

New view model structs have been added to the internal REST transport layer to handle request validation, DTO conversion, and response serialization for account management, authentication, and transfers, alongside a generic pagination helper. These models define the JSON structure and validation rules for API inputs (such as account creation and login) and outputs (including account details, transfer records, and paginated lists), ensuring consistent data formatting and Swagger documentation generation for the REST endpoints.

internal/transport/rest/viewmodel · high confidence

New REST route utility package for request handling and response formatting

The internal/transport/rest/routeutils package introduces standardized helpers for the REST layer. It provides generic parameter extraction (GetRequiredParam) with specific converters for IDs that reject zero and negative values, ensuring invalid IDs never reach downstream services. Paging parameters are now normalized with safe defaults (page 1, quantity 10, max 1000). Context propagation for account and session data is centralized in GetContext. Response helpers (ResponseCreated, ResponseAPIOk, HandleError) standardize JSON responses and error mapping using the apperr library. The package also defines an IRoute interface for route registration and EchoGroups for separating public and private route groups.

internal/transport/rest/routeutils · high confidence

New domain contracts and account entity with balance logic

This change introduces the internal domain contracts for caching, cryptography, repositories, and application services, establishing the interfaces for the system's core capabilities. It also adds the Account entity with methods to manage balance (add, subtract, check sufficiency) and includes unit tests for these operations. Additionally, the Transfer entity is refined to use UUIDs for account references instead of IDs, and its timestamp field is renamed to CreatedAt.

internal/domain/contract · high confidence

New number utility with generic rounding and string cleaning

Added a new \util/number\ package that provides a generic \RoundFloat\ function for both \float32\ and \float64\ types to resolve floating-point precision errors during arithmetic operations, and a \CleanNumber\ function to strip non-numeric characters from strings. Comprehensive unit tests were added to verify correct rounding behavior across various edge cases, including subtraction, addition, multiplication, and division imprecisions.

util/number · high confidence

New shutdown package for graceful server termination

A new \infra/shutdown\ package has been introduced to manage application lifecycle. It provides a \Context\ function that listens for OS termination signals (SIGINT, SIGTERM, SIGHUP, SIGQUIT) and cancels a context to trigger graceful shutdowns, and a \Stop\ function that ensures the gRPC server stops gracefully and the network listener is closed.

infra/shutdown · high confidence

New structured logger with automatic session and account context attributes

The infrastructure now uses a new logger implementation that automatically enriches log entries with session and account UUID attributes extracted from the request context. This change ensures that logs are consistently tagged with key identifiers, improving traceability and debugging capabilities for users and operators.

infra/logger · high confidence

REST server implementation using Echo v5 and goswag

The REST transport layer has been implemented in a new server.go file, migrating the HTTP framework to Echo v5 and integrating the goswag library for routing and Swagger documentation. The server initializes with configurable ports (defaulting to 5000), sets up CORS, registers specific route groups for account, auth, transfer, and ping endpoints, and includes Prometheus metrics middleware. It also configures client IP extraction based on headers and handles graceful shutdown with a 10-second timeout.

internal/transport/rest · high confidence

Removals

Removal of CPF validation utility

The \util/validator\ package has been removed, eliminating the \CleanNumber\ and \IsValidCPF\ functions that previously handled CPF (Brazilian individual taxpayer registry) format validation and number cleaning. Applications relying on this utility for validating CPF strings will no longer have access to these specific validation capabilities.

util/validator · high confidence

Removal of MySQL data access layer

The MySQL-specific repository implementation and connection management code in the \infra/data/mysql\ directory has been removed. This includes the deletion of files handling account and transfer data operations, database instance initialization, transaction handling, and interface definitions, effectively eliminating the MySQL data persistence layer from this component.

infra/data/mysql · high confidence

Removal of MySQL migration definitions

The MySQL migration logic has been removed from the codebase. The file \infra/data/migrations/mysql.go\, which previously defined database schema changes for tables like \tab\_account\ and \tab\_transfer\ using the darwin library, has been deleted. This indicates that MySQL-specific migration handling is no longer supported or maintained in this location.

infra/data/migrations · high confidence

Removal of REST server initialization and routing logic

The file application/rest/server.go has been deleted, removing the code responsible for initializing the Echo HTTP server, configuring CORS, setting up JWT middleware, and registering route handlers for ping, accounts, auth, and transfers. This change eliminates the previous implementation of the REST application entry point and its associated router infrastructure from this location.

application/rest · high confidence

Removal of REST viewmodel definitions

The REST viewmodel layer has been removed, deleting the \account.go\, \auth.go\, and \transfer.go\ files that previously defined request/response structures and validation logic for accounts, authentication, and transfers. This eliminates the local validation implementations (including CPF cleaning and validation) and the dependency on the \go\_utils-lib\ validation package within this package.

application/rest/viewmodel · high confidence

Removal of account route controller and router implementation

The account route controller and router files have been deleted from the application. This removes the HTTP endpoint definitions for creating accounts, listing accounts, retrieving account details by ID, and fetching account balances, along with the associated controller logic that handled request binding, validation, and mapping to view models.

application/rest/routes/accountroute · high confidence

Removal of application/factory/factory.go service initialization

The file application/factory/factory.go, which previously provided a singleton accessor (GetDomainServices) for initializing and retrieving domain services (Account, Auth, Transfer) along with configuration and mapping dependencies, has been deleted. This change removes the centralized service instantiation logic from this location, implying that service initialization is now handled elsewhere or via a different mechanism.

application/factory · high confidence

Removal of contract package interfaces

The \contract\ package has been removed, eliminating the \DataManager\, \MySQLRepo\, \AccountRepo\, and \MysqlTransaction\ interfaces that previously defined the data access layer. This change removes the abstraction layer for MySQL repository operations, including account management and transfer handling, from the codebase.

contract · high confidence

Removal of legacy authentication route implementation

The authentication route controller and router files have been deleted from the application. This removes the previous login endpoint implementation, which relied on a mapper library for transforming authentication responses, effectively cleaning up the codebase by eliminating this specific route handling logic.

application/rest/routes/authroute · high confidence

Removal of legacy domain service implementations

The account, authentication, and transfer service implementations have been removed from the domain/service package. This deletion eliminates the previous logic for account creation, login, and fund transfers, which relied on MD5 hashing for passwords and the external go-crypto-layer for encryption. These files are no longer part of the application codebase.

domain/service · high confidence

Removal of legacy route utility helpers

The \request.go\ and \response.go\ files in the \routeutils\ package have been removed, eliminating legacy helper functions for extracting context and parameters (\GetContext\, \GetAndValidateParam\) and standardizing API response formatting (\ResponseNoContent\, \ResponseCreated\, \ResponseAPIOK\, \HandleAPIError\). Users relying on these specific utility functions for request handling and error response generation in REST endpoints will need to adopt alternative implementations or updated patterns provided by the refactored route utilities.

application/rest/routeutils · high confidence

Removal of transfer route controller and router

The transfer route controller and router files have been deleted from the application. This removes the HTTP endpoints for adding and retrieving transfers, along with the associated controller logic that handled request binding, validation, and mapping using the go-mapper library.

application/rest/routes/transferroute · high confidence

Behavioural changes

The infrastructure/crypto module now uses the Argon2id algorithm with OWASP-recommended parameters (19 MiB memory, 2 iterations, 1 parallelism) for hashing and verifying passwords. This change replaces the previous implementation to improve security against GPU-based attacks and ensures that login attempts do not reveal whether an account exists by maintaining consistent hashing costs regardless of input validity.

infra/crypto · high confidence

Application layer restructured with new validation, security, and service contracts

The internal application layer has been reorganized into dedicated DTO and service packages, introducing input validation for account, authentication, and transfer operations via the \appvalidator\ library. Authentication behavior has been hardened to prevent account enumeration by using decoy password hashing and to track failed login attempts in the cache rather than the database, enforcing a lockout policy defined in domain constants. The service layer now relies on explicit infrastructure contracts and uses UUID v7 for generating unique identifiers.

internal/application · high confidence

Auth infrastructure refactored to PASETO tokens and Redis-based login lockout

The auth module has been rewritten to replace the previous JWT-based token generation with PASETO v4 symmetric encryption for access and refresh tokens, and to introduce a new login lockout mechanism that tracks failed attempts in Redis cache instead of the database. This change adds a \Lockout\ component that normalizes identities and enforces attempt ceilings within a configurable time window, and a \SignIn\ flow that uses a decoy hash to prevent user enumeration timing attacks. The old \auth.go\ file using \jwt-go\ has been removed, and the new implementation relies on the \LoginAttemptStore\ contract for cache-backed state.

infra/auth · high confidence

Auth middleware now rejects refresh tokens for access-protected routes

The REST server middleware in internal/transport/rest/serverMiddleware now strictly validates that tokens used for private routes are access tokens. Previously, a valid refresh token could pass verification; the new logic checks the token's Kind and returns an error if it is not an access token, preventing refresh tokens from being used where only access tokens are permitted. This change is accompanied by new tests covering the rejection of non-access tokens.

internal/transport/rest/serverMiddleware · high confidence

Centralized infrastructure configuration with connection pooling and lifecycle management

The configuration logic has been moved to the infra/config package, consolidating the management of application settings, database connections, caching, and tracing. This change introduces a centralized Config struct that loads settings from environment variables and config files, and explicitly applies database pool sizing parameters (max open connections, max idle connections, and max connection lifetime) to the PostgreSQL DSN to ensure connection limits are respected. Additionally, the new config system manages the lifecycle of infrastructure components by registering closers for the tracer, Redis cache, and PostgreSQL pool, ensuring proper cleanup on shutdown.

infra/config · high confidence

Database migration tooling now uses Goose with PostgreSQL support

The application now uses the Goose library to manage database migrations, replacing the previous local development approach. This change includes a shift to PostgreSQL as the database backend, with new command-line utilities added under cmd/ to handle both forward migrations (via cmd/main.go) and rollback operations (via cmd/migrate-down/main.go). Users can now reliably apply and revert schema changes using standardized SQL migration files managed by Goose.

cmd · high confidence

Introduction of structured authentication and account error codes

The system now defines specific, structured error codes for authentication failures (such as invalid credentials, deactivated accounts, and session issues) and account operations (such as CPF conflicts). These errors are standardized using the apperr library, providing consistent error types and machine-readable codes for better error handling and user feedback.

internal/domain/errcodes · high confidence

Introduction of typed authentication context keys

The infrastructure layer now defines a dedicated \Key\ type and specific constants for authentication context values, including \AccountUUIDKey\, \TokenKey\, and \SessionKey\. This change replaces raw string literals with strongly-typed keys for user access tokens and session data, improving type safety and clarity when accessing these values within the application's context.

infra · high confidence

Major architectural overhaul and infrastructure migration

The project has been restructured to follow Clean Architecture and Domain-Driven Design, moving the entry point to \cmd/main.go\ and organizing code into \internal\ (domain, application, transport) and \infra\ layers. The database backend has migrated from MySQL to PostgreSQL, and a Redis cache layer has been added for session management and rate limiting. Authentication security is enhanced with PASETO tokens and login attempt tracking in Redis. The development and deployment experience is improved with a new \Makefile\ for managing mocks and documentation, a TOML-based configuration system, and an expanded Docker Compose setup that includes Prometheus, Grafana, and Jaeger for observability.

(repo-wide) · high confidence

PostgreSQL data access layer for accounts and sessions

The \infra/data/postgres\ package now provides the concrete repository implementations for account and authentication data, replacing the previous MySQL-based approach. It introduces \accountRepo\ and \authRepo\ which persist account details (including CPF, balance, and password hashing) and manage user sessions (creation, retrieval, and blocking) against a PostgreSQL database using the \pgx\ driver. The implementation relies on a shared \queries\ helper embedded in repositories to standardize row scanning, support paginated reads via a \withCount\ SQL modifier, and map low-level database errors (such as \pgx.ErrNoRows\ and unique constraint violations) to application-level error codes. A \PostgresConn\ singleton manages the connection pool and exposes a \WithTransaction\ method that safely hands transaction-scoped repository instances to callers to prevent connection leaks.

infra/data/postgres · high confidence

REST routes migrated to Echo v5 with goswag documentation and explicit client IP resolution

The REST route handlers, routers, and middleware have been moved to the internal transport layer and upgraded to Echo v5. This change introduces explicit client IP resolution via a new \clientip\ package that prioritizes specific CDN headers (like \CF-Connecting-IP\) over the generic \X-Forwarded-For\ chain to prevent spoofing. Additionally, all route definitions now use \goswag\ to generate structured API documentation, and the authentication middleware has been updated to use the new \apperr\ error codes for consistent error handling.

internal/transport/rest/routes · high confidence

Regenerated mocks to use go.uber.org/mock and updated domain contracts

The mock files in the mocks package have been regenerated to reflect recent changes in the domain contract interfaces. The mocks now utilize the go.uber.org/mock/gomock library instead of the deprecated golang gomock. New or updated mocks include MockCacheManager (covering cache operations like Get, Set, Delete, and CleanAll), MockCrypto (for password hashing and verification), MockInfrastructure (exposing CacheManager, Crypto, DataManager, Logger, and Validator), MockRepos (including Account, Auth, and DataManager repositories with transaction support), and MockAccountApp/MockAuthApp (covering account management and session authentication). These changes ensure the test doubles remain consistent with the current internal domain contracts.

mocks · high confidence

Removal of MD5 hashing utility

The MD5 hashing function has been removed from the crypto utility package. This eliminates the ability to generate MD5 hashes for strings, which is a weaker cryptographic standard compared to modern alternatives.

util/crypto · high confidence

Removal of custom Docker entrypoint and MySQL service configuration

The custom entrypoint script that previously waited for the database before starting the application has been removed, and the dedicated Dockerfile for the MySQL service (which configured a specific user ID) has also been deleted. This change eliminates the custom startup logic and the specific MySQL container configuration defined in these files.

.docker · high confidence

Removal of custom SQL error checking utility

The \util/errors\ package, which previously provided the \SQLNotFound\ function to detect specific SQL errors like 'no rows in result set' via regular expressions, has been removed. This change eliminates the custom error-matching logic in favor of the SQL error checks now handled by \mysqlutils\, as indicated by the commit history.

util/errors · medium confidence

Removal of legacy JWT authentication middleware

The legacy JWT-based authentication middleware in the server middleware layer has been removed. This eliminates the previous mechanism that validated access tokens using the golang-jwt library and enforced login status for private routes, indicating a shift away from this specific JWT implementation strategy.

application/rest/serverMiddleware · high confidence

Removal of legacy configuration loader

The legacy configuration loading mechanism in \util/config/config.go\ has been removed. This file previously handled initialization of application settings, including JWT private keys and MySQL connection details, by reading from a \.env\ file using Viper. Its deletion indicates a migration to a new configuration strategy, likely the TOML-based dynamic loading and file-watching features introduced in other parts of the change set.

util/config · high confidence

Removal of legacy data initialization module

The \infra/data/data.go\ file, which previously provided a centralized \Connect\ function to initialize the MySQL repository and expose it via the \contract.DataManager\ interface, has been removed. This change eliminates the legacy data access layer in favor of the refactored infrastructure setup.

infra/data · high confidence

Removal of legacy domain entities and constants

The domain layer has been refactored by removing the \constants.go\ file (which defined \AuthErrorLimit\) and deleting the \Account\ and \Authentication\ entity structs from \domain/entity\. This cleanup eliminates the previous data models for account management and JWT-based authentication, aligning the domain structure with the new PASETO-based access token and session processes introduced in the same change set.

domain/entity · high confidence

Test coverage

Added GoMock mocks for authentication, cache, and Redis interfaces

Generated mock implementations for the \AuthToken\, \PasswordHasher\, \LoginAttemptStore\, and \IRedisCache\ interfaces have been added to the \infra/mocks\ package. These mocks, created via MockGen from their respective source interfaces in \infra/contract\ and \infra/cache\, enable unit testing of components that depend on authentication logic, password hashing, login attempt tracking, and Redis caching operations.

infra/mocks · high confidence

Dependencies

Major dependency upgrade and Go version bump

The project has upgraded the Go runtime from version 1.17 to 1.27.0 and performed a comprehensive update of its dependencies. This includes migrating the module path from github.com/diegoclair/go-boilerplate to github.com/diegoclair/go\_boilerplate, replacing the Echo v4 framework with Echo v5, switching the database driver from MySQL to PostgreSQL (jackc/pgx/v5), and updating internal libraries such as go\_utils, goswag, and apperr. The dependency graph was also significantly cleaned up, removing older indirect dependencies and introducing new ones for testing (testcontainers), observability (OpenTelemetry), and security (paseto).

(dependencies) · high confidence

Written by watchdog.canine.dev from the codebase's own history, inside the signed delivery this page is composed from.

How this codebase got here

Score

  • CAI 60 → 66 (+5.6)
  • Rubric changed (rubric-2026.09.15 → rubric-2026.10.1) — scores are not directly comparable.

Lenses

  • Code Health 100 → 90 (-9.9)
  • Architecture 83 (new)
  • Maturity 79 → 79 (+0.0)
  • Readiness 43 → 61 (+17.4)
  • Security 68 → 74 (+5.3)
  • Domain Modelling 61 (new)

Resolved (3)

  • Documentation: no contributor guidance (README.md)
  • Documentation: no installation or build instructions (README.md)
  • Documentation: no usage examples (README.md)

New (2)

  • Duplicated block (14 lines × 2) (infra/data/postgres/account.go)
  • Outdated: github.com/labstack/echo/v5

Changes since last survey

  • 1 commits — 0 feature/other, 1 fixes

By area

  • infra/auth — 1 commit

Notable commits

  • fix: fix(auth): refuse a token that was not minted for access

Written by watchdog.canine.dev from the codebase's own history, inside the signed delivery this page is composed from.

Survey your own repository

diegoclair/go_boilerplate was measured the same way every project in this corpus was: the same rubric, at a pinned commit, with the result published in full. Point a surveyor at a repository you know and see whether you agree with it.

About this page

  • The score is its most recent published measurement, taken on 6 October 2026 at a pinned commit. It is not a live figure and does not change until the project is measured again.
  • Measured at commit 7b53cf885498776d0c47cf329264f13521da408b — the exact code this score is about.
  • Scored under rubric-2026.10.1 — the same rubric and the same method as every other entry in this index.
  • Measured by watchdog.canine.dev using codehealth-analyzer preprod-8d8088103122.