This is a small template of a service written in Go, demonstrating:
- My modest vision of a convenient architecture of applications in Go
- Interaction with the database and the use of migrations
- Generation of API from the Swagger specification (this eliminates the discrepancy between documentation and code)
- Using mocks when writing unit tests
- Injection of dependencies using Wire
- Copy the
config.yml.dist
file toconfig.yml
- Run Docker containers:
make run_containers
- Apply migrations:
make migrate
- Run the service:
make run
- Open the Swagger UI: http://localhost:44444/v1/docs
- Use Swagger UI to interact with the API
- To stop the service, press
Ctrl+C
in the terminal
Dependency injection is implemented using Wire. To generate the DI code, run the following command:
make wire
Code generation is used here from the Swagger 2.0 specification. It is placed in the api/rest/swagger.yml file. Swagger 2 is used, not OpenAPI 3, because at the moment there are no API code generation libraries for Go that would fully cover the entire OpenAPI 3 specification. So I used go-swagger here because of it.
To generate the code from specification, run the following command:
make generate_server
Working with the database structure (creating tables, indexes, etc.) is done strictly through migrations.
- Create a file with the migration, for example:
goose -dir ./internal/storage/postgresql/migrator create create_table_article sql
.create_table_article
is an arbitrary migration name. Thesql
argument at the end of the command is needed to generate an SQL migration, not a Go file - In the
./internal/storage/postgresql/migrator/XXX_create_table_article.sql
file, write an SQL query for migration - Build the application
- Run the application with the
migrate
flag:./myapp migrate
When developing locally, migrations can be used like this: make migrate
.
Docker container with PostgreSQL must be running before it (see docker-compose.yml).