Clean Architecture
Clean Architecture Example
This example demonstrates a Go Fiber application following the principles of Clean Architecture.
Description
This project provides a starting point for building a web application with a clean architecture. It leverages Fiber for the web framework, MongoDB for the database, and follows the Clean Architecture principles to separate concerns and improve maintainability.
Requirements
Project Structure
api/: Contains the HTTP handlers, routes, and presenters.pkg/: Contains the core business logic and entities.main.go: The application entry point. It connects to MongoDB and sets up the routes.
Setup
Clone the repository:
git clone https://github.com/gofiber/recipes.git cd recipes/clean-architectureOptionally set the MongoDB connection string. The application reads
MONGO_URIfrom the environment (it does not load a.envfile) and defaults tomongodb://localhost:27017:export MONGO_URI=mongodb://localhost:27017Install the dependencies:
go mod downloadRun the application:
go run main.go
The API should now be running on http://localhost:3000.
API Endpoints
The following endpoints are available in the API:
- GET /api/books: List all books.
- POST /api/books: Add a new book.
- PUT /api/books: Update an existing book.
- DELETE /api/books: Remove a book.
Example Usage
Add a new book:
curl -X POST http://localhost:3000/api/books -d '{"title":"Book Title", "author":"Author Name"}' -H "Content-Type: application/json"List all books:
curl http://localhost:3000/api/booksUpdate a book:
curl -X PUT http://localhost:3000/api/books -d '{"id":"<book_id>", "title":"Updated Title", "author":"Updated Author"}' -H "Content-Type: application/json"Remove a book:
curl -X DELETE http://localhost:3000/api/books -d '{"id":"<book_id>"}' -H "Content-Type: application/json"
Replace <book_id> with the actual ID of the book.
Clean Architecture Principles
Clean Architecture is a software design philosophy that emphasizes the separation of concerns, making the codebase more maintainable, testable, and scalable. In this example, the Go Fiber application follows Clean Architecture principles by organizing the code into distinct layers, each with its own responsibility.
Layers in Clean Architecture
- Entities (Core Business Logic)
- Located in the
pkg/entitiesdirectory. - Contains the core business logic and domain models, which are independent of any external frameworks or technologies.
- Use Cases (Application Logic)
- Located in the
pkg/bookdirectory. - Contains the application-specific business rules and use cases. This layer orchestrates the flow of data to and from the entities.
- Interface Adapters (Adapters and Presenters)
- Located in the
apidirectory. - Contains the HTTP handlers, routes, and presenters. This layer is responsible for converting data from the use cases into a format suitable for the web framework (Fiber in this case).
- Frameworks and Drivers (External Interfaces)
- Located in
main.go. - Contains the application entry point and any external dependencies like the database connection and the web server setup.
Example Breakdown
- Entities: The
entities.Bookstruct represents the core business model for a book. - Use Cases: The
book.Serviceinterface defines the methods for interacting with books, such asInsertBook,UpdateBook,RemoveBook, andFetchBooks. - Interface Adapters: The
handlerspackage contains the HTTP handlers that interact with thebook.Serviceto process HTTP requests and responses. - Frameworks and Drivers: The
main.gofile initializes the Fiber application and sets up the routes using theroutes.BookRouterfunction.
Code Example
entities/book.go
package entities
import "go.mongodb.org/mongo-driver/bson/primitive"
type Book struct {
ID primitive.ObjectID `json:"id" bson:"_id,omitempty"`
Title string `json:"title"`
Author string `json:"author"`
}pkg/book/service.go
package book
import "clean-architecture/pkg/entities"
type Service interface {
InsertBook(book *entities.Book) (*entities.Book, error)
UpdateBook(book *entities.Book) (*entities.Book, error)
RemoveBook(ID string) error
FetchBooks() (*[]entities.Book, error)
}api/handlers/book_handler.go
package handlers
import (
"clean-architecture/pkg/book"
"clean-architecture/pkg/entities"
"clean-architecture/api/presenter"
"github.com/gofiber/fiber/v3"
"net/http"
"errors"
)
func AddBook(service book.Service) fiber.Handler {
return func(c fiber.Ctx) error {
var requestBody entities.Book
err := c.Bind().Body(&requestBody)
if err != nil {
c.Status(http.StatusBadRequest)
return c.JSON(presenter.BookErrorResponse(err))
}
if requestBody.Author == "" || requestBody.Title == "" {
c.Status(http.StatusBadRequest)
return c.JSON(presenter.BookErrorResponse(errors.New("Please specify title and author")))
}
result, err := service.InsertBook(&requestBody)
if err != nil {
c.Status(http.StatusInternalServerError)
return c.JSON(presenter.BookErrorResponse(err))
}
return c.JSON(presenter.BookSuccessResponse(result))
}
}main.go
package main
import (
"clean-architecture/api/routes"
"clean-architecture/pkg/book"
"github.com/gofiber/fiber/v3"
)
func main() {
app := fiber.New()
bookRepo := book.NewRepo(collection)
bookService := book.NewService(bookRepo)
api := app.Group("/api")
routes.BookRouter(api, bookService)
app.Listen(":3000")
}By following Clean Architecture principles, this example ensures that each layer is independent and can be modified or replaced without affecting the other layers, leading to a more maintainable and scalable application.
Conclusion
This example provides a basic setup for a Go Fiber application following Clean Architecture principles. It can be extended and customized further to fit the needs of more complex applications.