Framework Architecture β
Understanding the goserve framework architecture and design patterns.
Overview β
goserve is built on a feature-based architecture that promotes clean code, separation of concerns, and testability. The framework emphasizes each API being independent while sharing common services, reducing code conflicts in team environments.
It provides a recipe for building scalable RESTful APIs with built-in support to integrate for authentication, authorization, caching, and database interactions.
Core Principles β
- Feature Independence - Each API feature is organized in separate directories by endpoint
- Service Sharing - Common services can be shared across features while maintaining independence
- Layered Architecture - Clear separation between Controllers, Services, Models, and DTOs
- Testability - Architecture supports easy unit and integration testing
- Scalable Architecture - Modular design supports scaling and extension
- Authentication & Authorization - Built-in patterns for JWT and API key auth
Framework Code Organization β
.
βββ dto # Data Transfer Objects (input/output structs)
β βββ mongoid.go # Mongo ID helper for DTOs
β βββ pagination.go # Pagination DTO fields
β βββ slug.go # Slug generation DTO helper
β βββ uuid.go # UUID handling
β
βββ micro # Microservice-oriented code
β βββ controller.go # Microcontroller logic base
β βββ interfaces.go # Interfaces for micro handlers
β βββ message.go # Microservice message types
β βββ nats.go # NATS integration helpers
β βββ request.go # Microrequest helpers
β βββ router.go # Router setup for microservices
β βββ sender.go # Client code to send micro messages
β
βββ middleware # Request/response middleware
β βββ errorcatcher.go # Panic/recover middleware
β βββ notfound.go # β404 not foundβ handler
β
βββ mongo # Mongo database helpers
β βββ builder.go # Query builder utilities
β βββ database.go # DB connection & pooling
β βββ query.go # Generic query helpers
β βββ validation.go # Mongo validation logic
β
βββ postgres # Postgres database helpers (if used)
β βββ database.go # Postgres DB connection logic
β
βββ network # HTTP API layer utilities
β βββ apierror.go # Standard API error structs
β βββ controller.go # HTTP controller base
β βββ header.go # Header helpers
β βββ interfaces.go # HTTP interfaces (controllers, services)
β βββ parsers.go # Request parsing helpers
β βββ request.go # HTTP request helpers
β βββ response.go # HTTP response helpers
β βββ router.go # Route registration
β βββ sender.go # HTTP client helpers
β βββ validation.go # HTTP request validation
β
βββ redis # Redis caching helpers
β βββ cache.go # High-level cache API
β βββ store.go # Redis connection & operations
β
βββ utility # Generic helpers
βββ format.go # Data formatting utilities
βββ mapper.go # Struct mapping helpers
βββ random.go # Random value helpersLayered Architecture Pattern β
goserve follows a 4-layer architecture pattern that separates concerns while maintaining clean dependencies:
1. Controller Layer (Network Layer) β
Handles HTTP requests and responses, acts as the entry point:
Location: api/[feature]/controller.go
Responsibilities:
- Route definition and mounting
- Request parsing and validation
- Authentication and authorization checks
- Calling service layer methods
- Response formatting
- HTTP-specific logic handling
- Error response formatting
Key Pattern:
type controller struct {
network.Controller
// Other dependencies...
}
func NewController(
authProvider network.AuthenticationProvider,
authorizeProvider network.AuthorizationProvider,
// Other dependencies...
) network.Controller {
return &controller{
Controller: network.NewController("/auth", authProvider, authorizeProvider),
// Initialize other dependencies...
}
}
func (c *controller) MountRoutes(group *gin.RouterGroup) {
group.DELETE("/signout", c.Authentication(), c.signOutBasic)
}
func (c *controller) signOutBasic(ctx *gin.Context) {
// Parse request
// Call service method
// Format response
}2. Service Layer (Business Logic) β
Contains business logic and database interactions:
Location: api/[feature]/service.go
Responsibilities:
- Business rule enforcement
- Data transformation and validation
- Database operations coordination
- Cache management
- External service integration
Key Pattern:
type Service interface {
CreateBlog(d *dto.CreateBlog) (*model.Blog, error)
// Other service methods...
}
type service struct {
db postgres.Database,
cache redis.Cache[dto.BlogPublic],
}
func NewService(db postgres.Database) Service {
return &service{
db: db,
}
}
func (s *service) CreateBlog(dto *dto.CreateBlog) (*dto.BlogPublic, error) {
// Business logic validation
// Database operations
// Cache invalidation
// Return result
}3. Model Layer (Data Entities) β
Defines database schema and internal data structures:
Location: api/[feature]/model/[record].go
Responsibilities:
- Database table representation
- Data type definitions
- Field mapping documentation
- Internal domain entities
Key Pattern:
type Blog struct {
ID uuid.UUID // id
Title string // title
Description string // description
Text *string // text
AuthorID uuid.UUID // author_id
Status bool // status
CreatedAt time.Time // created_at
UpdatedAt time.Time // updated_at
}4. DTO Layer (Data Transfer Objects) β
Defines request/response contracts and API boundaries:
Location: api/[feature]/dto/[operation].go
Responsibilities:
- Input validation and sanitization
- Output formatting and filtering
- API contract documentation
- Sensitive data hiding
Key Pattern:
type BlogCreate struct {
Title string `json:"title" validate:"required,min=3,max=500"`
Description string `json:"description" validate:"required,min=3,max=2000"`
DraftText string `json:"draftText" validate:"required,max=50000"`
Tags []string `json:"tags" validate:"required,min=1,dive,uppercase"`
}
type BlogPublic struct {
ID uuid.UUID `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
Tags []string `json:"tags"`
Author *UserInfo `json:"author"`
PublishedAt time.Time `json:"publishedAt"`
}Recommended Framework Implementation β
Recommended implementation patterns for building APIs with goserve for a production-ready architecture.
Complete Request Lifecycle β
HTTP Request
β
Root Middleware (Global)
βββ Error Catcher
βββ API Key Authentication
βββ Not Found Handler
β
Router (Gin)
β
Feature Route Group (/api/blog)
β
Authentication Middleware (JWT)
βββ Extract Bearer Token
βββ Verify RSA Signature
βββ Validate Claims & Expiry
βββ Load User from Database
βββ Set User Context
β
Authorization Middleware (Roles)
βββ Check User Permissions
βββ Validate Required Roles
βββ Allow/Deny Access
β
Controller Handler
βββ Parse Request Body (DTO)
βββ Validate Input
βββ Call Service Method
β
Service Layer (Business Logic)
βββ Business Rule Validation
βββ Database Operations
βββ Cache Management
βββ External Service Calls
β
Controller Handler
β
Response Formatting
βββ Success (200-299)
βββ Client Error (400-499)
βββ Server Error (500-599)Middleware Chain Details β
Authentication Middleware (protected routes):
- JWT token extraction and validation
- User context loading
Authorization Middleware (role-protected routes):
- Permission checking
- Role validation
- Access control
Feature-Based Organization β
goserve organizes code by business features rather than technical layers, making it easier for teams to work independently:
Feature Organization Principles β
Independent Features: Each feature is self-contained with its own directory:
api/auth/ # Complete auth feature
api/blog/ # Blog management featureShared Resources: Related features can share models and DTOs:
api/blog/
βββ dto/ # Shared between author/editor features
βββ model/ # Shared database models
βββ service.go # Shared business logicClear Boundaries: Features communicate through well-defined interfaces, not direct dependencies.
Dependency Injection & Module System β
goserve uses a module-based dependency injection system that wires all components together:
Module Pattern β
The module interface enables clean dependency injection:
type Module interface {
GetInstance() *module
Controllers() []network.Controller
RootMiddlewares() []network.RootMiddleware
AuthenticationProvider() network.AuthenticationProvider
AuthorizationProvider() network.AuthorizationProvider
}Benefits β
- Clean Architecture: Clear component relationships
- Testability: Easy mocking of dependencies
- Flexibility: Easy to swap implementations
- Maintainability: Centralized dependency management
Error Handling β
Consistent error handling across the framework:
- Structured error responses
- HTTP status code mapping
- Error logging and tracking
Configuration Management β
Environment-based configuration:
- Environment variables
- Configuration files
- Default values
- Type-safe config access
Testing Support β
Built-in support for testing:
- Test server utilities
- Mock generators
- Integration test helpers
Microservices Support β
goserve's modular architecture supports scaling to larger applications through service extraction and component reuse.
Performance Considerations β
- Connection Pooling: Optimized database connections
- Caching Strategy: Redis integration with cache-aside pattern
- Efficient Routing: Gin-based routing with minimal overhead
- Horizontal Scaling: Stateless services ready for scaling
Testing Architecture β
goserve supports comprehensive testing at all levels:
