Minimum Gin starter template for REST API.
This template uses
By default it uses Postgres connection. If you are using different Database, you can easily change the dsn, check GORM: Connecting to a Database
This template uses air with hot reload feature in development environment. Read the installation guide here.
- Copy
.env.example
to.env
and modify the env value as needed go mod download
to install all required dependenciesair .air.toml
: start a dev server with hot reload (auto updates swagger)go test -v ./...
: run all tests on all packages
Note: set GO_ENV
to production
to run Gin app in release mode
To access swagger documentation, open http://localhost:3000/swagger/index.html on your browser. Read more about swag's comment annotation here
GET http://localhost:3000/api/compA
:"Hello World"
GET http://localhost:3000/api/compA/3/5
:
{
"result": 8
}
.
├── compA
│ ├── models.go
│ ├── router.go
│ ├── service.go
│ └── service_test.go
├── compB
│ └── ...
├── main.go
├── go.mod
└── ...
This template separate your code by your app's components, for example for a social media app, you will have something like this:
.
├── posts
│ └── ...
├── users
│ └── ...
├── main.go
├── go.mod
└── ...
Each component will usually contains 4 files:
models.go
: contains the component's GORM Models (notice that it'smodels.go
, notmodel.go
it's because one component can have more than one model, for example forposts
component, you can havePost
model andComment
model, though you can also separatecomments
into it's own component folder)router.go
: contains api routes and it's controllerservice.go
: contains the business logic of the component (avoid putting business logic directly in router to make testing easier)service_test.go
: contains tests for yourservice.go