An example project of Golang + Ports and Adapters structure on top of https://github.com/golang-standards/project-layout and https://github.com/yuraxdrumz/golang-starter-kit
- git clone
[email protected]/yuraxdrumz/ports-and-adapters-golang
- Create database folder project's root for sqlite adapter
- go mod init
- go run main.go
Ports and Adapters divides your code to 3 parts:
- Business-logic - These are your business rules + types, implemented without any dependency on 3rd party modules (self-contained)
- Ports - Interfaces to speak with your business rules
- Adapters - Implementations of the ports, There are two kinds of adapters:
- In(Driver) - your external API to the world. For example -
internal/pkg/adapters/in/http.go
- Out(Driven) - what your business logic uses. For example -
internal/pkg/adapters/out/reverser/in-memory.go
- In(Driver) - your external API to the world. For example -
Usually, you divide ports
and adapters
to separate directories, but the best practice in golang is to keep structs near implementations. That is why, I decided to add ports.go
near each adapter.
Adding a new business logic:
- Create appropriate ports in
ports.go
file underinternal/app/your-use-case/ports.go
- Create your use-case with your application specific logic under
internal/app/your-use-case/logic.go
- Create your in/out adapter, for example -
Repository(out)
orgRPC(in)
.internal/pkg/adapters/*
- Tests!!!
your-file-name_test.go
under same directory as fileinternal/app/your-use-case/logic_test.go