Golang: A Todo App using GIN

Gin is a web framework written in Go(Golang). If you need performance and good productivity, use Gin, you’ll love it.

Ekta Garg
Jul 28 · 4 min read
GIN: Most popular framework in Golang

Gin is a high-performance micro-framework that can be used to build web applications. It allows you to write middleware that can be plugged into one or more request handlers or groups of request handlers.

It is the most popular framework in Golang. Look at the picture above, this framework has the highest no. of stars on Github.com

Goals

By the end of this tutorial, you will:

  • Learn how to use Gin to create RESTful APIs (we will be creating a TODO application), and
  • Understand the parts of a web application written in Go.

Prerequisites

For this tutorial, you will need Go and postman installed on your machine.

Note: If you don’t have postman, you can use any other tool that you would use to test API endpoints.

List of Packages we are going to use:

go get github.com/go-sql-driver/mysql
go get github.com/gin-gonic/gin
go get github.com/jinzhu/gorm

Project Structure:

Project structure for GIN-TODO-APP

List of APIs:

GET: /v1/todo 
POST: /v1/todo
GET: /v1/todo/:id
PUT: /v1/todo/:id
DELETE: /v1/todo/:id

Let’s start working, I would suggest you write each n every line of code by yourself, this way you’ll understand things better. So we’ll start by creating a project called GIN-TODO-APP.

Setup Database

GORM is an ORM library written in Golang which we are using in our project. In this config file, we will be creating a function called BuildDBConfig() where you can set up your DB host, port, username, password, and dbname and pass it to DbURL() to create your database URL.

Set up DB for Todo project using GIN

Table and Schema

Let’s talk about DB Structure and schema. For this project, we’ll be having just one table ‘todo’. This table will have id, title, description as its attributes.

TableName() function will be used wherever we need to access the table name.

Todo table structure

Setup routes and list of APIs

Here, we are going to set up a router using

r := gin.Default()

Default returns a gin Engine instance with the Logger(write the logs to gin.DefaultWriter) and Recovery middleware already attached but if you need to start a blank gin instance with middleware attached, you should use gin.New()

v1 := r.Group("/v1")

You can group multiple routes using Group() function, these APIs will be accessible on /v1

Set up API Routes for Todo project using GIN

Models: Database queries

Let’s write all the Database queries which we will be required to create APIs which includes: fetching all the records from table todo, insert a record, fetch a specific record, update an existing record, delete a record.

DB Queries: fetch all, fetch one, insert, update, delete

Create an API: POST Todo

GIN provides methods(Must bind, Should bind) to bind request body into type which supports JSON, XML, YAML and form values.

c.BindJSON(&todo)

So here it will bind request body to Models.Todo (when binding from JSON, set json:"fieldname") which is to:

type Todo struct {
ID uint `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
}

We can add validations to this struct as well, for eg: binding:”required” will return an error if it has empty value while binding.

Make a DB call to create a todo which is being handled by CreateATodo() written in Models/Todo.go. If it returns an error, call AbortWithStatus which calls `Abort()` and writes the error code (We are using net/http package for StatusNotFound and StatusOK codes).

POST API to create a TODO
APIs: POST, GET, PUT, DELETE

RUN the server

Let’s get ready to combine DB config, Models, Routes, APIs into main.go. gorm.Open() initialize a new DB connection:

db, err := gorm.Open("mysql", "user:password@/dbname?charset=utf8&parseTime=True&loc=Local")

AutoMigrate() automatically migrates your schema, to keep your schema update to date.

One thing to note here is that AutoMigrate() will only create tables, missing columns and missing indexes, and won’t modify existing column’s data/type.

db.AutoMigrate(&Models.Todo{})

Setup the routes and run the server. Run() will listen and serve on 8080 by default.

r.Run()
main.go

Perfect!! We are all set now. Let’s run this project:

go run main.go

And I can see an Engine instance has been created and the APIs are running:

A running GO server

Let’s hit our first POST API:

So, It’s a SUCCESS!

Create a TODO: POST

Likewise, all are APIs are working as expected. If you find any kind of difficulty following the above steps, please check this repo and run:

git clone https://github.com/ektagarg/gin-gorm-todo-app

If you have any insight, respond here! Otherwise, I hope this article helped you answer how to setup GIN, GORM and create RESTful APIs. Thanks for reading and stay tuned!

Ekta Garg

Written by

Ekta Garg

A feminist by nature, a developer by profession, and a blogger by passion. Follow me to follow my journey (only technical as of now)

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade