Go Language, MYSQL - Simple Rest CRUD API example
In this article, we will show you how to develop a REST-style web service with Go Language and MYSQL.
These are APIs that Spring backend App will export:
- GET all User's : /users
- GET User by ID : /users/{id}
- POST User : /users
- PUT User : /users
- DELETE User : /users/{id}
Technologies used:
- Go Language
- MYSQL Database
- gorilla/mux
- jinzhu/gorm
gorilla/mux: The gorilla/mux package provides request routing, validation, and other services.
jinzhu/gorm: The gorm is an ORM library for the Go language.GORM provides CRUD operations and can also be used for the initial migration and creation of the database schema.
Final Project Structure:
Let's start building the application
Create database 'userdb':
CREATE DATABASE userdb;
Initialize the Go project:
Initialize the Go project using the following command
go mod init rest-crud-api-go-lang
Adding the modules required for the project:
go get github.com/gorilla/mux
go get github.com/jinzhu/gorm
go get github.com/go-sql-driver/mysql
Entity [user.go]:
package entity
type User struct {
ID int `json:"id" gorm:"primary_key"`
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
Email string `json:"email"`
}
Database Configuration [dbconfig.go]:
package config
import (
"fmt"
"log"
"rest-crud-api-go-lang/entity"
"github.com/jinzhu/gorm"
)
func InitDB() {
config :=
Config{
ServerName: "localhost:3306",
User: "root",
Password: "",
DB: "userdb",
}
connectionString := GetConnectionString(config)
err := Connect(connectionString)
if err != nil {
panic(err.Error())
}
//Migrate database table
Connector.AutoMigrate(&entity.User{})
log.Println("Table migrated")
}
type Config struct {
ServerName string
User string
Password string
DB string
}
var GetConnectionString = func(config Config) string {
connectionString := fmt.
Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&"+
"collation=utf8mb4_unicode_ci&"+
"parseTime=true&multiStatements=true",
config.User, config.Password, config.ServerName, config.DB)
return connectionString
}
var Connector *gorm.DB
//MySQL connection
func Connect(connectionString string) error {
var err error
Connector, err = gorm.Open("mysql", connectionString)
if err != nil {
return err
}
log.Println("Connection was successful!!")
return nil
}
router [httprouter.go]:
package router
import (
"rest-crud-api-go-lang/controller"
"github.com/gorilla/mux"
)
func InitaliseHandlers(router *mux.Router) {
router.HandleFunc("/users",
controller.CreateUser).Methods("POST")
router.HandleFunc("/users",
controller.GetAllUser).Methods("GET")
router.HandleFunc("/users/{id}",
controller.GetUserByID).Methods("GET")
router.HandleFunc("/users",
controller.UpdateUserByID).Methods("PUT")
router.HandleFunc("/users/{id}",
controller.DeletUserByID).Methods("DELETE")
}
controller [usercontroller.go]:
package controller
import (
"encoding/json"
"io/ioutil"
"net/http"
dbconfig "rest-crud-api-go-lang/config"
"rest-crud-api-go-lang/entity"
"strconv"
"github.com/gorilla/mux"
)
//Fetch all user get all User data
func GetAllUser(w http.ResponseWriter, r *http.Request) {
var users []entity.User
dbconfig.Connector.Find(&users)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(users)
}
//Get user by id returns User with specific ID
func GetUserByID(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
key := vars["id"]
var user entity.User
dbconfig.Connector.First(&user, key)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(user)
}
//Create user
func CreateUser(w http.ResponseWriter, r *http.Request) {
requestBody, _ := ioutil.ReadAll(r.Body)
var user entity.User
json.Unmarshal(requestBody, &user)
dbconfig.Connector.Create(user)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(user)
}
//Update user by id
func UpdateUserByID(w http.ResponseWriter, r *http.Request) {
requestBody, _ := ioutil.ReadAll(r.Body)
var user entity.User
json.Unmarshal(requestBody, &user)
dbconfig.Connector.Save(&user)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(user)
}
//Delet user by id
func DeletUserByID(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
key := vars["id"]
var user entity.User
id, _ := strconv.ParseInt(key, 10, 64)
dbconfig.Connector.Where("id = ?", id).Delete(&user)
w.WriteHeader(http.StatusNoContent)
}
main [main.go]:
package main
import (
"log"
"net/http"
"rest-crud-api-go-lang/config"
routers "rest-crud-api-go-lang/router"
"github.com/gorilla/mux"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
func main() {
config.InitDB()
log.Println("Starting the HTTP server on port 9080")
router := mux.NewRouter().StrictSlash(true)
routers.InitaliseHandlers(router)
log.Fatal(http.ListenAndServe(":9080", router))
}
Run:
go run main.go
Verify:
Create User:
Update User:
Fetch all Users:
Get User by Id:
Delete User:
Developer: Joy