This tutorial will walk you through the steps to build a CRUD RESTful APIs example by using Golang, Go Modules, Wire, Gin, Gorm and MySQL

About the tech stack

Prerequisites

  • This example's tested on Go 1.13 and MySQL 8+

Init project structure and dependencies

  • The project's packaged in business functionality instead of technicalities
├── product
│   ├── product.go
│   ├── product_api.go
│   ├── product_dto.go
│   ├── product_mapper.go
│   ├── product_repository.go
│   └── product_service.go
├── go.mod
├── go.sum
├── main.go
├── wire.go
└── wire_gen.go
  • The dependencies are defined in the go.mod file at the project root directory

  • You can find the wire.go and wire_gen.go in the latter part of this tutorial

Create model, repository and service

Create model


gorm.Model is an embedded model defining common fields including ID, CreatedAt, UpdatedAt and DeletedAt

Create repository


Create service


Create DTO, mapper and API

Create DTO


Create Mapper


Create API


Wire things together

Create wire.go to inject dependencies


In the command line, run $GOPATH/bin/wire at the same location of wire.go to generate the wire_gen.go file

Create main.go to bootstrap the app


Build, run and test

You can type the following commands at the project root directory to build and run

  • Build the project with go build. It will generate an execute file rest-gin-gorm

  • Type the following command to run, replace root:123456 with your MySQL Server username and password, replace test with your database name

PORT=8080 DB_URL="root:[email protected]/test?charset=utf8&parseTime=True&loc=Local" ./rest-gin-gorm

You can test the APIs by using [HTTPie] (https://httpie.org/) command line

  • Find all products http localhost:8080/products
  • Find a product http localhost:8080/products/1
  • Create a new product http POST localhost:8080/products code=p1 price=10
  • Update a product http PUT localhost:8080/products/1 code=p1 price=100
  • Delete a product http DELETE localhost:8080/products/1

Conclusion

In this tutorial, we learned using Go Modules, Wire, Gin, and Gorm to build a CRUD RESTful APIs example. You can find the full source code at here