Goyave Web Framework

website·Indexed 32 days ago

https://goyave.dev

An 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.

Tokens
46.8K
Snippets
197
Records
315
Agent score
57%

What's inside Goyave

  1. Overview of the Goyave Golang Framework

    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.
  2. 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: Handles 422 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.

  3. 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.
  4. 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.
  5. Handle breaking changes and removals in Goyave v5

    v5.0.0.html

    Several packages and functions have been removed to reduce bloat and improve architecture:

    • Removed Packages: util/sliceutil (use samber/lo instead) and the ratelimit package.
    • 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).
  6. Understand Goyave's unified logging system

    Goyave uses a custom wrapper around Go's standard *slog.Logger to unify logs from the framework, Gorm, and the application. This ensures a consistent format and a single io.Writer output (defaulting to os.Stderr).

    Key behaviors include:

    • Log Levels: Supports Debug, Info, Warn, and Error.
    • Default Handler: Uses *slog.JSONHandler by default.
    • Dev Mode: When app.debug = true in 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.
  7. Handle application panics with Recovery middleware

    Goyave includes a built-in global recovery middleware that catches unrecovered panic calls. The middleware:

    1. Wraps the panic into a *errors.Error (if not already wrapped).
    2. Logs the error with a full stack trace.
    3. Sets the response status to http.StatusInternalServerError (500).
    4. Executes the configured status handler for the 500 code.
  8. Use the Session Abstraction for Business Transactions

    v5.0.0.html
    The 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.
  9. 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>.go for implementation and a validation.go for rules.
      • middleware/: Application middleware, with one file per middleware.
      • route/: Contains route.go for the main route registration function.
      • validation/: Custom validator implementations.
    • Domain Layer (service/): Contains service implementations. Each service should have its own package. service/service.go is 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
  10. 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 during goyave.New() and can be accessed via server.DB(). This pool is available to all framework components.
  11. 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.Create method 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.
  12. Implement Websocket controllers

    v5.0.0.html

    Websockets now use a component-based architecture. Instead of lone handlers, they use controllers that implement the websocket.Controller interface, which requires a Serve(*websocket.Conn, *goyave.Request) error method.

    Key changes:

    • Upgraders are created via websocket.New(controller).
    • Controllers can implement the websocket.Registrer interface to manually register upgrade routes.
    • Configuration options like UpgradeErrorHandler, ErrorHandler, CheckOrigin, and Headers are now interfaces implemented by the controller.
    • Connection close timeout is configured via server.websocketCloseTimeout.