An API server example using Echo with Swagger.
- Go Framework - Echo
- RESTful API doc generater - echo-swagger
- Environment Variables - GoDotEnv
Detail : go.mod
Note : The dependency of repository on domain should be fixed.
flowchart LR
subgraph Presentation
id1["handlers/"]
end
subgraph Application
services/
end
subgraph Domain
domains/
end
subgraph Repository
repositorys/
end
Presentation --> Application
Application --> Domain
Application --> Repository
Repository --> Domain
| key | value |
|---|---|
| handlers | controller, routing |
| services | usecase, Application Logic |
| repository | data store |
| docs | API documents to generated with Swagger |
| configs | Not in use now |
Create go.sum:
go mod tidy- Run
go run .to start server. - Open http://localhost:3000 with your browser to see the result.
- Open http://localhost:3000/swagger/index.html, you can see Swagger Api documents.
Request (GET):
curl 'http://localhost:3000/albums'Response body:
[
{
"id": 1,
"title": "Blue Train",
"artist": "John Coltrane",
"price": 56.99
},
{
"id": 2,
"title": "Jeru",
"artist": "Gerry Mulligan",
"price": 17.99
},
{
"id": 3,
"title": "Sarah Vaughan and Clifford Brown",
"artist": "Sarah Vaughan",
"price": 39.99
}
]Request (POST):
curl -X POST 'http://localhost:3000/albums' -H 'Content-Type: application/json' -d '{"id":4, "title":"Sun", "artist":"Apple", "price":10.12}'Response body:
AcceptedThe environment is determined by .env.
development: (.env .development):
APP_ENV=developmentother: (.env .inmemory):
APP_ENV=inmemoryIf "development" is selected, the datastore is a MySQL server. and a Docker container must be started for MySQL. =>
Otherwise, the datastore is in-memory and no DB server is required.
Note: .env should normally be added to .gitignore.
- Install Swag
go install github.com/swaggo/swag/cmd/swag@lates-
Write API annotations to go file. (Swagger Document)
-
Run
swag initand generate API documents in/docsdirectory.
swag init- Restart Server.
docker-compose up -d| key | host | port | view |
|---|---|---|---|
| app | 127.0.0.1 | 3000 | http://localhost:3000/ |
| db | 127.0.0.1 | 3306 | |
| adminer | 127.0.0.1 | 8080 | http://localhost:8080/ |
If you want a go execution environment container, use the app container. After the container shell is started, the prescribed flow is simply performed within the container.
go test ./handlers/ -vIn the go test command for handlers, the data store is always in-memory.
More Code Design.