Goyave Web Framework
website·Indexed 32 days ago
https://goyave.devAn opinionated all-in-one Golang web framework. It features a component-based architecture, routing with subrouters and controllers, middleware support, and built-in services for authentication (including JWT and Basic auth), localization, and validation. The framework provides a structured approach to application lifecycle management, including a dedicated data layer with repositories and DTO mapping.
What's inside Goyave
- Goyave is an opinionated, all-in-one Golang web framework specifically designed for building enterprise REST APIs. It emphasizes code reliability, maintainability, and developer experience by providing a strong architecture and built-in conventions. Key features include advanced error handling, recovery, and a comprehensive suite of tools for routing, controllers, middleware, validation, authentication, and database ORM, allowing developers to focus on business logic rather than technical infrastructure.
Overview of Goyave Status Handlers
Status handlers are components executed during the finalization step of a request's lifecycle if a status code has been set but the response body is empty. They provide a centralized way to handle specific response status codes, typically used for user errors (400s) or server errors (500s).
Goyave includes three built-in handlers by default:
goyave.PanicStatusHandler: Handles errors and panics (500).goyave.ErrorStatusHandler: Handles non-success codes (400s, 501+).goyave.ValidationStatusHandler: Handles422 Unprocessable Entity(validation errors).
Note: The 500 status handler is an exception and will execute even if an error or panic occurs after a write has already started.
Overview of the Goyave framework
Goyave is an opinionated, all-in-one Golang web framework specifically focused on building REST APIs. It is designed for medium to large projects requiring enterprise-level clean architecture, emphasizing code reliability, maintainability, and developer experience (DX).
Core Goals:
- Reduce setup friction with an all-in-one package.
- Allow developers to focus on business logic rather than technical infrastructure.
- Provide a robust, resilient, and hackable setup for real-world applications.
- Maintain extensive documentation to reduce cognitive load for developers.
Non-Goals (What Goyave is NOT for):
- Hyper-optimization or extreme performance tuning.
- Small projects or quick prototypes.
- Low-level networking control.
- Front-end development tools.
Goyave design philosophy
Goyave is an opinionated framework for building REST APIs. Its core goals are:
- Simplicity & Flexibility: Making common cases (like resource permissions) easy to implement while remaining "hackable" and flexible for edge cases.
- Developer Focus: Reducing boilerplate and repetitive setup so developers can focus on business logic.
- Enterprise Quality: Striving for a level of quality that allows both independent developers and companies to build large-scale applications with confidence.
Handle breaking changes and removals in Goyave v5
v5.0.0.htmlSeveral packages and functions have been removed to reduce bloat and improve architecture:
- Removed Packages:
util/sliceutil(usesamber/loinstead) and theratelimitpackage. - Removed Functions:
utils.Map, and maintenance mode functions (goyave.EnableMaintenance(),goyave.DisableMaintenance(),goyave.IsMaintenanceEnabled()). Maintenance mode should now be handled by the proxy layer. - Go Version: The minimum supported Go version is now 1.21 (the second-to-latest version).
- Removed Packages:
Understand Goyave's unified logging system
Goyave uses a custom wrapper around Go's standard
*slog.Loggerto unify logs from the framework, Gorm, and the application. This ensures a consistent format and a singleio.Writeroutput (defaulting toos.Stderr).Key behaviors include:
- Log Levels: Supports
Debug,Info,Warn, andError. - Default Handler: Uses
*slog.JSONHandlerby default. - Dev Mode: When
app.debug = truein the config, a custom human-readable handler is used instead of JSON. - Error Enrichment: The wrapper automatically enriches error logs using the framework's error system.
- Log Levels: Supports
Handle application panics with Recovery middleware
Goyave includes a built-in global recovery middleware that catches unrecovered
paniccalls. The middleware:- Wraps the panic into a
*errors.Error(if not already wrapped). - Logs the error with a full stack trace.
- Sets the response status to
http.StatusInternalServerError(500). - Executes the configured status handler for the 500 code.
- Wraps the panic into a
Use the Session Abstraction for Business Transactions
v5.0.0.htmlThe session mechanism provides an abstraction over transactions, allowing services to control business transactions across multiple repositories or services without direct database interaction. This prevents side-effects and allows sessions to be mocked for testing complex failure scenarios.Organize a Goyave project using the recommended directory structure
Goyave recommends a layered architecture separating the data layer, presentation layer, and domain layer to maintain a clean separation of concerns.
Layer Breakdown
- Data Layer (
database/): Contains migrations, models, repositories, and optional seed files. - Presentation Layer (
http/): Handles HTTP-specific logic.controller/: Feature-based packages (e.g.,http/controller/user). Each package typically contains a<feature>.gofor implementation and avalidation.gofor rules.middleware/: Application middleware, with one file per middleware.route/: Containsroute.gofor the main route registration function.validation/: Custom validator implementations.
- Domain Layer (
service/): Contains service implementations. Each service should have its own package.service/service.gois used to define constants for service names. - DTOs (
dto/): Contains Data Transfer Object structures, with one file per feature. - Resources (
resources/): Stores static assets and language files. Do not use this for dynamic user-uploaded content.
Localization Setup
Language files are stored in
resources/lang/{language-code}/using ISO 639-1 codes (case-sensitive, e.g.,en-US). Each language directory can optionally contain:fields.json: Field name translations and field-specific rule messages.locale.json: General language lines.rules.json: Validation rule messages.
. ├── database (Data layer) │ ├── migrations │ ├── model │ ├── repository │ └── seed (optional) ├── dto │ └── user.go ├── http (Presentation layer) │ ├── controller │ │ └── user │ │ ├── user.go │ │ └── validation.go │ ├── middleware │ ├── route │ │ └── route.go │ └── validation ├── resources │ └── lang │ └── en-US │ ├── fields.json (optional) │ ├── locale.json (optional) │ └── rules.json (optional) ├── service (Domain layer) │ ├── user │ │ └── user.go │ └── service.go ├── config.json ├── go.mod ├── main.go └── README.md- Data Layer (
Access and manage database connections in Goyave
Goyave uses the Gorm ORM and manages database connections as long-lived pools. Connections are automatically closed when the server shuts down. The connection pool is initialized duringgoyave.New()and can be accessed viaserver.DB(). This pool is available to all framework components.Understand the role of Repositories in Goyave
Repositories are part of the Data layer and are responsible for executing unitary database operations (fetch, create, update, delete).
Key constraints for Repositories:
- No Business Logic: Repositories must not implement business logic; this is the responsibility of the Service layer.
- Unitary Operations: Each repository method should execute only one database operation. For example, a
user.Createmethod should only create the user, not associated history entries. - Dependencies: Repositories must not depend on services, although they can depend on other repositories.
- Data Interaction: They interact with the database using Models, which are Go representations of the database schema.
Implement Websocket controllers
v5.0.0.htmlWebsockets now use a component-based architecture. Instead of lone handlers, they use controllers that implement the
websocket.Controllerinterface, which requires aServe(*websocket.Conn, *goyave.Request) errormethod.Key changes:
- Upgraders are created via
websocket.New(controller). - Controllers can implement the
websocket.Registrerinterface to manually register upgrade routes. - Configuration options like
UpgradeErrorHandler,ErrorHandler,CheckOrigin, andHeadersare now interfaces implemented by the controller. - Connection close timeout is configured via
server.websocketCloseTimeout.
- Upgraders are created via