Clean Architecture using Golang

Update

I published an updated version of this post. Check it out at: Clean Architecture, 2 years later

What is Clean Architecture?

In his book “Clean Architecture: A Craftsman’s Guide to Software Structure and Design” famous author Robert “Uncle Bob” Martin presents an architecture with some important points like testability and independence of frameworks, databases and interfaces.

The constraints in the Clean Architecture are :

  • Independent of Frameworks. The architecture does not depend on the existence of some library of feature laden software. This allows you to use such frameworks as tools, rather than having to cram your system into their limited constraints.

More at https://8thlight.com/blog/uncle-bob/2012/08/13/the-clean-architecture.html

So, based on this constraints, every layer must be independent and testable.

From Uncle Bob’s Architecture we can divide our code in 4 layers :

  • Entities: encapsulate enterprise wide business rules. An entity in Go is a set of data structures and functions.

Clean Architecture in Golang

Let’s use as an exemple the package user:

In the file entity.go we have our entities:

In the file repository.go we have the interface that define a repository, where the entities will be stored. In this case the repository means the Framework & Driver layer in Uncle Bob architecture. His content is:

This interface can be implemented in any kind of storage layer, like MongoDB, MySQL, and so on. In our case we implemented using MongoDB, as seen in mongodb.go:

The file service.go represents the Use Case layer, as defined by Uncle Bob. In the file we have the interface Service and his implementation. The Service interface is:

The last layer, the Controller in our architecture is implemented in the content of api:

In the following code, from api/main.go, we can see how to use the services:

Now we can easily create tests to our packages, like:

Using the Clean Architecture we can change the database from MongoDB to Neo4j, for instance, without breaking the rest of application. And we can grow our software without losing quality and speed.

References

https://hackernoon.com/golang-clean-archithecture-efd6d7c43047

https://8thlight.com/blog/uncle-bob/2012/08/13/the-clean-architecture.html

Teacher, speaker, Tech Manager @ Trybe. https://eltonminetto.dev