First, you need to have Go installed. Follow the instructions here. Or simply use brew:
brew install go
go version
mkdir gin-riders-api
cd gin-riders-api
go mod init gin-riders-api
go get github.com/gin-gonic/gin
touch main.go
code .
In the main.go
file, let's create a basic server
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.GET("/", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"data": "Hello API"})
})
r.Run(":3000")
}
let's run this basic server:
go run main.go
curl http://localhost:3000 // in another terminal
note: to run this server in a production env, you may want to set GIN_MODE=release
We're going to use the ORM called Gorm
so, the first step is to download the package:
go get gorm.io/gorm
go get -u gorm.io/driver/sqlite
Let's create some models to communicate with the DB. Models are implemented as structs
in Go. Add the following to a file called models/rider.go
:
type Rider struct {
ID uint `json:"id" gorm:"primary_key"`
Name string `json:"name"`
Age int8 `json:"age"`
Phone string `json:"phone"`
BloodType string `json:"blood_type"`
}
Once our models are defined, we need to establish commu ication with our DB and keep our models in sync witn the DB's schema. We do this by having the following code in separate file, models/setup.go
:
package models
import (
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func SetupModels() *gorm.DB {
db, err := gorm.Open(sqlite.Open("local.db"), &gorm.Config{})
if err != nil {
panic("Failed to connect to database!")
}
db.AutoMigrate(&Rider{}) // keep the DB in sync with our models
return db
}
├── controllers
│ ├── health.go
│ └── riders.go
├── db
│ └── db.go
├── go.mod
├── go.sum
├── main.go
├── middlewares
├── models
│ └── rider.go
├── server
│ ├── router.go
│ └── server.go
└── test.db