Gost is a robust boilerplate and starter kit designed for building scalable backend applications in Golang. By drawing heavy inspiration from the modular architecture and design patterns of features of NestJS, Gost brings structure, order, and developer ergonomics to your Go web applications.
It provides a ready-to-use environment completely configured with a powerful HTTP framework, an ORM, caching, decoupled validation, centralized error handling, and file uploads. Everything is orchestrated in a familiar way to developers transitioning from the Node/NestJS ecosystem, bringing the strong typing and high performance of Go.
- NestJS-like Architecture: Logical separation of concerns through Modules, Controllers, Services, and Repositories.
- Dependency Injection pattern: Clean and manual wiring of dependencies keeping the codebase tightly coupled only where it needs to be.
- Built-in Validation: Class-validator style validation using Go Generics and struct tags (
Pipes). - Gost CLI: A powerful command-line tool for project initialization, module scaffolding, and automatic CRUD generation.
- Global Error Handling: Centralized exception filtering to avoid leaking panics and standardizing API error JSON responses (
Filters). - Middleware Abstractions: Simple interfaces for
Interceptors(request logging/modification) andGuards(authentication/authorization). - Advanced Security: Integrated JWT with Access/Refresh tokens, Redis-based blacklisting, and RBAC (Role-Based Access Control).
- Internationalization (i18n): Out-of-the-box support for multi-language APIs, localized validation errors, and dynamic locale detection via headers.
- Communication & Real-time: Fully integrated RabbitMQ for async processing, Websockets (Hub/Client) for real-time interaction, and secure Webhooks with HMAC signatures and auto-retries.
- Data Protection: Hardened password hashing with Bcrypt and AES-256-GCM field-level encryption.
- Resilience: Redis-powered Rate Limiting to prevent DDoS and brute-force attacks.
- CORS Configured: Out-of-the-box support for frontend consumers (SPA-friendly). Dynamically configured via the
ALLOWED_CORSenvironment variable logic. - File Upload Support: Built-in utility for handling
multipart/form-datauploads. - Database & Cache Ready: Pre-configured with PostgreSQL (via GORM) and Redis, easily testable via Docker Compose.
- Web Framework: Gin Web Framework
- Database ORM: GORM
- Messaging: RabbitMQ (AMQP)
- Caching & State: Go-Redis
- Security: JWT, Bcrypt, AES-256-GCM
- Containerization: Docker & Docker Compose
Gost recreates the building blocks of modern backend frameworks utilizing Go's native constructs and the Gin framework context.
Modules group related domain entities, logic, and networking (e.g., Users, Products, Orders) into a cohesive block. Each module exposes an InitModule function, acting as the module's wiring board (similar to the @Module decorator), setting up and injecting dependencies.
- Controllers (
*.controller.go): Handle incoming HTTP requests, extract parameters/body, and format responses. They delegate logic processing. - Services (
*.service.go): Protect the core business logic. Agnostic of HTTP rules. - Repositories (
*.repository.go): The persistence layer. Handles direct database interactions (GORM), abstracting the DB logic from the Service.
Middlewares that wrap route handlers. Use them for request logging, mapping payloads, tracking execution time, or even mutating the response context (e.g., LoggerInterceptor).
Middlewares dedicated exclusively to authorization and authentication fluxes. The provided AuthGuard checks for valid tokens before allowing the request's execution pipeline to proceed.
Global exception filters. If a controller encounters an error, it shouldn't need to format the error manually. By bubbling it up via c.Error(err), the globally attached ErrorHandler intercepts it and formats an elegant JSON response identical to NestJS's HttpException.
Used for input payload serialization and syntax validation. Gost leverages Go Generics in pipes.ValidateBody[DTO](c) to parse JSON bodies directly into typed DTOs and validate them strictly based on Gin's binding tags.
Gost provides out-of-the-box support for:
- Websockets: Persistent bidirectional communication using a central Hub.
- RabbitMQ: Asynchronous message production and consumption (Scaffolding ready).
- Webhooks: Reliable event dispatching with HMAC signatures and exponential backoff retries.
Security is baked into the framework core:
- JWT Auth: Access tokens and Refresh tokens managed via Redis.
- RBAC: Protect your routes using
Guards.RolesGuard("admin"). - Rate Limit: Stop brute force attacks with the built-in Redis rate limiter.
- Encryption: Built-in utilities for Bcrypt hashing and AES-256 encryption.
A centralized translation system:
- Middleware: Detects user locale from
Accept-Languageheaders. - Localized Validation: Automatically translates struct validation errors (e.g., "Field required" to "Campo obrigatΓ³rio").
- Dynamic Messages: Effortlessly translates responses based on
.jsonlocale files.
To run and develop on this project, ensure you have installed:
- Go >= 1.21
- Docker & Docker Compose
- Git
Pick your favorite way to install the Gost CLI:
Ideal for Linux, macOS, and Git Bash:
curl -sSL https://gost.run/install.sh | shInstall directly from source into your $GOPATH/bin:
go install github.com/JsCodeDevlopment/gost/cmd/gost@latestbrew install JsCodeDevlopment/tap/gostnpx gost-cli init my-projectIf you need to remove the Gost CLI from your system, follow the steps for your installation method:
On Windows (PowerShell):
Remove-Item $Env:USERPROFILE\go\bin\gost.exeOn Linux/macOS:
rm $(which gost)brew uninstall JsCodeDevlopment/tap/gostIf you installed it globally via npm:
npm uninstall -g gost-cliOtherwise, simply clear your npx cache (optional):
npx clear-npx-cacheOnce installed, you don't need to clone the repository ever again. The Gost CLI is standalone and carries the framework within it.
Bootstrap a new project in seconds with an interactive prompt. You can choose a Full template (all modules included) or Basic (pick exactly what you need).
Interactive:
gost init my-apiNon-interactive:
gost init my-api --template Basic --modules auth,i18nScaffolds a clean directory structure for a new domain.
gost make:module ordersCreates: src/modules/orders/{dto,entities,repositories,services} and orders.module.go.
The ultimate productivity booster. Generates a complete domain module with Entity, DTOs, Repository, Service, and Controller, and automatically registers it in app.module.go.
gost make:crud productWorkflow Flow:
- Run
make:crud <name>. - The CLI detects your project name from
go.mod. - Files are generated with correct imports.
InitModuleis called inapp.module.go.- Your REST API is live! (Just restart the server).
gost/
βββ main.go // Application entry point (Bootstrap)
βββ docker-compose.yml // Infrastructure definitions (Postgres, Redis, RabbitMQ)
βββ src/
β βββ app/
β β βββ app.module.go // Main registrar (mounts routes, configs, middlewares)
β βββ common/
β β βββ filters/ // Global Error Handling
β β βββ guards/ // Authentication, JWT, and RBAC Middlewares
β β βββ i18n/ // Internationalization (Middleware, Providers, Validators)
β β βββ interceptors/ // Request flow modifications, Logging, Rate Limiting
β β βββ messaging/ // RabbitMQ Producers, Consumers, and Webhook Workers
β β βββ pipes/ // Payload Validations logic
β β βββ security/ // Cryptographic utils (Bcrypt, AES-256)
β β βββ utils/ // Utilities (File Upload, Webhook Dispatcher)
β βββ config/
β β βββ database.go // Database configuration
β β βββ rabbitmq.go // Messaging broker setup
β β βββ redis.go // Cache configuration
β βββ modules/
β βββ auth/ // JWT Identity management (Login, Refresh, Logout)
β βββ ws/ // Websocket Hub and Client management
β βββ users/ // [Example] Domain Module
β βββ dto/ // Payload validation and input schemas
β βββ entities/ // Database models
β βββ users.controller.go
β βββ users.module.go
β βββ users.repository.go
β βββ users.service.go
The recommended way to create a module is using the Gost CLI. However, if you prefer doing it manually:
- Create a folder
src/modules/products. - Following the NestJS pattern, segregate your files:
entities/: Define your generic entity models (e.g.,product.entity.go).dto/: Put your request payload structs here.exceptions/,presenters/,queries/, andtests/: Scaffold these directories to keep concerns separated as the module grows.
- At the root of the module folder (
src/modules/products/):- Scaffold the core layers:
products.repository.go,products.service.go,products.controller.go(andproducts.consumer.goif parsing messages from queues). - Wire them inside
products.module.gomapping from DB to Repo, Service to Controller.
- Scaffold the core layers:
- Create
products.module.gocontainingfunc InitModule(router *gin.RouterGroup)to manually wire these layers together. Register yourPOST,GEThandlers here. - Finally, register the new module in
src/app/app.module.go:products.InitModule(apiGroup).
Create a DTO with struct tags for automated validation:
type CreateProductDto struct {
Name string `json:"name" binding:"required,min=3"`
Price float64 `json:"price" binding:"required,gt=0"`
}Use the Pipe in your controller:
func (ctrl *ProductController) Create(c *gin.Context) {
// Throws a beautifully handled 400 Bad Request if fields are invalid
dto, err := pipes.ValidateBody[CreateProductDto](c)
if err != nil {
return
}
// dto is strongly typed as *CreateProductDto
product, err := ctrl.service.Create(*dto)
// ...
}POST /api/v1/auth/login- Authenticate and receive Access & Refresh tokensPOST /api/v1/auth/logout- Invalidate current session (Redis Blacklist)
GET /api/v1/users- List all users (Example of Repository pattern)GET /api/v1/users/:id- Fetch user detailsPOST /api/v1/users- Create a new user (Validates Email & Name size)PUT /api/v1/users/:id- Update user detailsDELETE /api/v1/users/:id- Delete a userPOST /api/v1/users/:id/avatar- Upload a user avatar image (multipart/form-data)
To explore the full potential of the library, we've created a directory with explanatory guides teaching step-by-step the inner workings behind Gost. If you want to learn how to extract 100% from every file, keep reading:
- 01 - Introduction and Architectural Philosophy
- 02 - Bootstrap and Server Configurations
- 03 - Building Modules, Injection and Domain-Driven
- 04 - DTOs, Security with Pipes and ORM (Entities)
- 05 - Shields: Filters, Auth Guards and Interceptors
- 06 - Utilities: Micro-Caching and File Uploads
- 07 - Deployment and Hosting Strategy
- 08 - Testing Strategies (Unit & E2E)
- 09 - Security Deep Dive: Authenticity and Protection
- 10 - Communication and Connectivity (RabbitMQ, WS, Webhooks)
- 11 - Internationalization (i18n): Multi-language Support
- 12 - Gost CLI Automation: Productivity & Scaffolding
Contributions make the open-source community an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated. If you have a fix or suggestion, please open a pull request.
- Fork the Project
- Create your Feature Branch (
git checkout -b feature/AmazingFeature) - Commit your Changes (
git commit -m 'feat: Add some AmazingFeature') - Push to the Branch (
git push origin feature/AmazingFeature) - Open a Pull Request
- Formatting: Follow standard Go formatting (
go fmt/gofumpt). - Architecture: Respect the established decoupled design and layers boundaries. Controllers shouldn't call logic directly.
- Commits: Try using Conventional Commits.
| Foto | Nome | Cargo |
|---|---|---|
| Jonatas Silva | Senior Software Engineer / CTO at PokerNetic |
Distributed under the MIT License. See LICENSE for more information.
