What is ORM?
ORM stands for Object-Relational Mapping (ORM) is a programming technique for converting data between relational databases and object oriented programming languages such as Java, C#, etc.
What is GORM?
The GORM is fantastic ORM library for Golang, aims to be developer friendly. It is an ORM library for dealing with relational databases. This gorm library is developed on the top of database/sql package.
The overview and feature of ORM are:
- Full-Featured ORM (almost)
- Associations (Has One, Has Many, Belongs To, Many To Many, Polymorphism)
- Callbacks (Before/After Create/Save/Update/Delete/Find)
- Preloading (eager loading)Transactions
- Composite Primary Key
- SQL Builder
- Logger
- Developer Friendly
GORM officially supports databases MySQL, PostgreSQL, SQLite, SQL Server.
Connect Database
In this post, we will use Postgres to store our data. Before continue, your computer have to install Postgres. If you want to know further more about Postgres and how to install. This is my post about Postgres: Postgres Introduction.
Let's install GORM
and Postgres driver, run:
go get -u gorm.io/gorm
go get -u gorm.io/driver/postgres
Now, you can use GORM
and Postgres
in your project.
package mainimport (
"fmt"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
func main(){ dsn := "host=localhost user=gorm password=gorm dbname=gorm port=9920 sslmode=disable TimeZone=Asia/Shanghai"
_, err := gorm.Open(postgres.Open(dsn), &gorm.Config{}) if err != nil {
fmt.Println("Fail to connect db. Error : " + err.Error())
}
fmt.Println("Connect database successfully!")})
API CRUD
Define simple Post
struct:
type Post struct {
Id int `json:"id" gorm:"column:id;"`
Title string `json:"title" gorm:"column:title;"`
Description string `json:"description" gorm:"column:description;"`
}
Create API get list Post
Create API get Post
by id
Create API create new Post
Create API update Post
by id
Create API delete Post
by id
Summary
Writing CRUD restful APIs using Go can be easy and fast, and with the help of Gorm adapter, our api data which is food order in this post can be saved to our database and retrieved it back easily. Thank You.
Full source code: https://github.com/tinhuynh1/go-crud
References: