Project to show clean architecture in Go using a Holidays backend example
brew install go
brew install sqlite
Create a SQLlite table on gorm.db file
sqlite3 gorm.db 'CREATE TABLE holidays ( id INTEGER PRIMARY KEY, year INTEGER NOT NULL, name TEXT NOT NULL, date TEXT NOT NULL );'
(Optional) Create a holiday record
sqlite3 gorm.db "INSERT INTO holidays VALUES (1, 2024, 'Example', '2024-01-01 00:00:00+00:00')"
Run the example
go run main.go
Create a new holiday
curl --request POST \
--url http://localhost:3000/holiday \
--header 'Content-Type: application/json' \
--data '{
"year": 2023,
"name": "new year",
"date": "2023-01-01T00:00:00Z"
}'
Read holidays by year
curl --request GET \
--url http://localhost:3000/holiday/2023
Principal tasks are included in the makefile:
- Test:
make test
- Test with coverage:
make testcov
- Open coverage html report:
make opencov
- Show coverage result:
make showcov
- Go vet, the golang analizer for suspicious constructs:
make govet
- Staticcheck, state of the art linter for the Go:
make staticcheck
Most of these tasks will be running on the CI pipeline
For use the staticcheck you will need:
go install honnef.co/go/tools/cmd/staticcheck@latest
Clean Architecture was presented by Uncle Bob (Robert C. Martin) on 2012 as a compilation of different ideas, like Hexagonal Architecture, Onion Architecture, etc, that produce similar advantages.
We will not explore the details of the architecture here, but we will explain how this example follow the clean diagram.
Inside src
folder we are separating folder following domain groups idea. This tiny example only have one domain (holiday). Each domain folder have a Clean Architecture structure like:
entities
: Contains the business rules and entities. Holiday entity is compound of a Name and the holiday Dateusecases
: Contains the exposed features or use cases that the business need. For example, it is exposed the Holiday Creation and Retrieveinterfaceadapter
: Contains the http controllers and its own details that use the features exposed byusecases
registry
: Part of frameworks and drivers. Contains the details to generate the web controllerinfra
: Contains the details of DB and Router implementation
- Clean Architecture by Uncle Bob (Robert C. Martin)
- Clean Architecture with go
- Clean architecture by domains
export PATH="$PATH:$(go env GOPATH)/bin"