Run project

go run main.go

Open the web browser and goto http://localhost:8080

Testing

Get All Products

Click the \\\"Get Products\\\" button. The API will return all products data.

\\\"Create

Get Product By Id

Click the \\\"Get Product\\\" button and enter \\\"1\\\" for the product id. The API will return a product data.

\\\"Create

Create Product

Click the \\\"Create Product\\\" button and enter \\\"test-create\\\" for the product name and \\\"100\\\" for the price. The API will return a newly created product.

\\\"Create

Update Product

Click the \\\"Update Product\\\" button and enter \\\"101\\\" for the product id and \\\"test-update\\\" for the name and \\\"200\\\" for the price. The API will return an updated product.

\\\"Create

Delete Product

Click the \\\"Delete Product\\\" button and enter \\\"101\\\" for the product id. The API will return nothing, which is acceptable as we do not return anything from our API.

\\\"Create

Conclusion

In this article, you have learned how to create and settings up the Gin framework in order to create a CRUD API. Utilize GORM as an ORM to perform the CRUD operations on the database. Test our API using JavaScript. I hope you will enjoy the article.

Source code: https://github.com/StackPuz/Example-CRUD-Go

Create a CRUD Web App: https://stackpuz.com

","image":"http://www.luping.net/uploads/20240815/172373328366be1523a3829.jpg","datePublished":"2024-08-15T22:48:03+08:00","dateModified":"2024-08-15T22:48:03+08:00","author":{"@type":"Person","name":"luping.net","url":"https://www.luping.net/articlelist/0_1.html"}}
"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Create a CRUD API with Go

Create a CRUD API with Go

Published on 2024-08-15
Browse:431

Create a CRUD API with Go

The CRUD operations (create, read, update, delete) are the basic functionality of any web application when working with a database. This example will show you how to create the CRUD API with Go and using MySQL as a database.

Prerequisites

  • Go 1.21
  • MySQL

Setup project

Setting up the Go project dependencies.

go mod init app
go get github.com/gin-gonic/gin
go get gorm.io/gorm
go get gorm.io/driver/mysql
go get github.com/joho/godotenv

Create a testing database named "example" and run the database.sql file to import the table and data.

Project structure

├─ .env
├─ main.go
├─ config
│  └─ db.go
├─ controllers
│  └─ product_controller.go
├─ models
│  └─ product.go
├─ public
│  └─ index.html
└─ router
   └─ router.go

Project files

.env

This file contains the database connection information.

DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=example
DB_USER=root
DB_PASSWORD=

db.go

This file sets up the database connection using GORM. It declares a global variable DB to hold the database connection instance to use later in our application.

package config

import (
    "fmt"
    "os"

    "github.com/joho/godotenv"
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
    "gorm.io/gorm/schema"
)

var DB *gorm.DB

func SetupDatabase() {
    godotenv.Load()
    connection := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true", os.Getenv("DB_USER"), os.Getenv("DB_PASSWORD"), os.Getenv("DB_HOST"), os.Getenv("DB_PORT"), os.Getenv("DB_DATABASE"))
    db, _ := gorm.Open(mysql.Open(connection), &gorm.Config{NamingStrategy: schema.NamingStrategy{SingularTable: true}})
    DB = db
}

router.go

This file sets up routing for a Gin web application. It initializes a router, serves a static index.html file at the root URL, defines API routes for CRUD operations.

package router

import (
    "app/controllers"

    "github.com/gin-gonic/gin"
)

func SetupRouter() {
    productController := controllers.ProductController{}
    router := gin.Default()
    router.StaticFile("/", "./public/index.html")
    router.Group("/api").
        GET("/products", productController.Index).
        POST("/products", productController.Create).
        GET("/products/:id", productController.Get).
        PUT("/products/:id", productController.Update).
        DELETE("/products/:id", productController.Delete)
    router.Run()
}

product.go

This file defines the Product model for the application. This model is used for database operations involving products.

package models

type Product struct {
    Id int `gorm:"primaryKey;autoIncrement"`
    Name string
    Price float64
}

product_controller.go

This file defines all functions required to handle incoming requests and perform any CRUD operations.

package controllers

import (
    "app/config"
    "app/models"
    "net/http"
    "strconv"

    "github.com/gin-gonic/gin"
)

type ProductController struct {
}

func (con *ProductController) Index(c *gin.Context) {
    var products []models.Product
    config.DB.Find(&products)
    c.JSON(http.StatusOK, products)
}

func (con *ProductController) Get(c *gin.Context) {
    var product models.Product
    config.DB.First(&product, c.Params.ByName("id"))
    c.JSON(http.StatusOK, product)
}

func (con *ProductController) Create(c *gin.Context) {
    var product models.Product
    c.BindJSON(&product)
    if err := config.DB.Create(&product).Error; err != nil {
        c.AbortWithError(http.StatusBadRequest, err)
        return
    }
    c.JSON(http.StatusOK, product)
}

func (con *ProductController) Update(c *gin.Context) {
    var product models.Product
    c.BindJSON(&product)
    product.Id, _ = strconv.Atoi(c.Params.ByName("id"))
    if err := config.DB.Updates(&product).Error; err != nil {
        c.AbortWithError(http.StatusBadRequest, err)
        return
    }
    c.JSON(http.StatusOK, product)
}

func (con *ProductController) Delete(c *gin.Context) {
    var product models.Product
    if err := config.DB.Delete(&product, c.Params.ByName("id")).Error; err != nil {
        c.AbortWithError(http.StatusBadRequest, err)
        return
    }
    c.Status(http.StatusOK)
}

c.BindJSON() parse the JSON payload from the request body into a Go struct.

config.DB the GORM instance that use to perform the desired database operation.

c.JSON() send a JSON response with the result of the operation and the appropriate HTTP status code.

main.go

This file is the main entry point of our application. It will create and setting up the Gin web application.

package main

import (
    "app/config"
    "app/router"
)

func main() {
    config.SetupDatabase()
    router.SetupRouter()
}

index.html

This file will be used to create a basic user interface for testing our API.


    

Example CRUD

Release Statement This article is reproduced at: https://dev.to/stackpuz/create-a-crud-api-with-go-964?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3