Clean Architecture using Golang

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 :

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 :

Clean Architecture in Golang

Let’s use as an exemple the package user:

ls -ln pkg/user
-rw-r — r — 1 501 20 5078 Feb 16 09:58 entity.go
-rw-r — r — 1 501 20 3747 Feb 16 10:03 mongodb.go
-rw-r — r — 1 501 20 509 Feb 16 09:59 repository.go
-rw-r — r — 1 501 20 2403 Feb 16 10:30 service.go

In the file entity.go we have our entities:

ca-1

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:

ca-2

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:

ca-3

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:

ca-4

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

cd api ; tree
.
|____handler
| |____company.go
| |____user.go
| |____address.go
| |____skill.go
| |____invite.go
| |____position.go
|____rice-box.go
|____main.go

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

ca-5

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

ca-6

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 https://github.com/eminetto/clean-architecture-go