Skip to content

Instantly share code, notes, and snippets.

@federico-garcia
Last active November 2, 2021 06:52
Show Gist options
  • Save federico-garcia/b7bfbc8057a0e9ce5123c4a6b504970d to your computer and use it in GitHub Desktop.
Save federico-garcia/b7bfbc8057a0e9ce5123c4a6b504970d to your computer and use it in GitHub Desktop.
Building an API with Gin

Gin Web Framework

Installation

First, you need to have Go installed. Follow the instructions here. Or simply use brew:

brew install go
go version

Setting up the project

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

Setting uo DB access

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
}

Project structure

├── 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment