go-gin mysql_使用GO,GIN,MySql的CRUD API

go-gin mysql

GO has been around for a quite long time now. It is considered as one of the fastest programming language with high performance. In this article, I will be sharing how I wrote CRUD API using GO. Technologies used in this article are GO, Gin, GORM and Mysql.

GO已经存在了很长时间。 它被认为是具有高性能的最快的编程语言之一。 在本文中,我将分享如何使用GO编写CRUD API。 本文使用的技术是GO,Gin,GORM和Mysql。

Gin is a web framework written in Go (Golang). It features a martini-like API with performance that is up to 40 times faster thanks to httprouter.

Gin是用Go(Golang)编写的Web框架。 它具有类似于martini的API,其性能比httprouter快40倍。

GORM is a ORM library for GOlang.

GORM是用于GOlang的ORM库。

I am providing the github link to the repository for this article.

我为本文提供了到存储库的github链接

So let’s start writing CRUD API now. Create a new GO project and install the related dependencies. We install GORM, Gin and Mysql by running following commands.

因此,让我们现在开始编写CRUD API。 创建一个新的GO项目并安装相关的依赖项。 我们通过运行以下命令来安装GORM,Gin和Mysql。

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

For setting up our Mysql database. We can add the following piece of code.

用于设置我们的Mysql数据库。 我们可以添加以下代码。

package modelsimport (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
)// SetupDB : initializing mysql databasefunc SetupDB() *gorm.DB {
USER := "root"
PASS := "password"
HOST := "localhost"
PORT := "3306"
DBNAME := "bookCRUD"
URL := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", USER, PASS, HOST, PORT, DBNAME)db, err := gorm.Open("mysql", URL)if err != nil {
panic(err.Error())
}return db}

For the sake of simplicity, I have left the user ,password and other credentials hard coded. You can load it from env file too. We connect to mysql using the gorm.Open.

为了简单起见,我已经对用户,密码和其他凭据进行了硬编码。 您也可以从env文件加载它。 我们使用gorm.Open连接到mysql。

Now we create our first model. We can create our model by using following code.

现在,我们创建第一个模型。 我们可以使用以下代码创建模型。

// models/book.go
package modelstype Task struct {ID uint `json:"id" gorm:"primary_key"`AssingedTo string `json:"assignedTo"`Task string `json:"task"`}

Nothing much here, we just have id, assigedto and task field. Id is unique int whereas assignedto and task are strings.

这里没什么,我们只有id,assigedto和Task字段。 id是唯一的int,而assignedto和task是字符串。

Now,we move towards configuring our routes for the API. Generally, we make a separate file for routes but to keep it short, I have added the routes in the main.go file. It can look something like this.

现在,我们开始为API配置路由。 通常,我们为路由创建一个单独的文件,但为了简短起见,我在main.go文件中添加了路由。 它看起来可能像这样。

package mainimport (
"bookCRUD/controllers"
"bookCRUD/models"
"net/http"
"github.com/gin-gonic/gin"
)func main() {
r := gin.Default()
db := models.SetupDB()
db.AutoMigrate(&models.Task{})
r.Use(func(c *gin.Context) {
c.Set("db", db)
})r.GET("/", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"data": "hello world"})
})
r.GET("/tasks", controllers.FindTasks)
r.POST("/tasks", controllers.CreateTask)
r.GET("/tasks/:id", controllers.FindTask)
r.PATCH("/tasks/:id", controllers.UpdateTask)
r.DELETE("tasks/:id", controllers.DeleteTask)
r.Run()
}

We can now make controllers that handles the request on the routes configured. The controllers file can be something like this.

现在,我们可以使控制器在配置的路由上处理请求。 控制器文件可以是这样的。

// controllers/books.gopackage controllersimport (// "bookc/models"
"bookCRUD/models"
"net/http"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm")type CreateTaskInput struct {
AssingedTo string `json:"assignedTo"`
Task string `json:"task"`
}type UpdateTaskInput struct {
AssingedTo string `json:"assignedTo"`
Task string `json:"task"`
}// GET /tasks// Get all tasks
func FindTasks(c *gin.Context) {
db := c.MustGet("db").(*gorm.DB)
var tasks []models.Task
db.Find(&tasks)
c.JSON(http.StatusOK, gin.H{"data": tasks})
}// POST /tasks// Create new taskfunc CreateTask(c *gin.Context) {
// Validate input
var input CreateTaskInput
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}// Create tasktask := models.Task{AssingedTo: input.AssingedTo, Task: input.Task}
db := c.MustGet("db").(*gorm.DB)
db.Create(&task)
c.JSON(http.StatusOK, gin.H{"data": task})
}// GET /tasks/:id// Find a taskfunc FindTask(c *gin.Context) { // Get model if exist
var task models.Task
db := c.MustGet("db").(*gorm.DB)if err := db.Where("id = ?", c.Param("id")).First(&task).Error; err != nil {c.JSON(http.StatusBadRequest, gin.H{"error": "Record not found!"})
return
}c.JSON(http.StatusOK, gin.H{"data": task})}// PATCH /tasks/:id// Update a taskfunc UpdateTask(c *gin.Context) {db := c.MustGet("db").(*gorm.DB)// Get model if existvar task models.Taskif err := db.Where("id = ?", c.Param("id")).First(&task).Error; err != nil {c.JSON(http.StatusBadRequest, gin.H{"error": "Record not found!"})return}// Validate input
var input UpdateTaskInput
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}db.Model(&task).Updates(input)c.JSON(http.StatusOK, gin.H{"data": task})
}// DELETE /tasks/:id// Delete a taskfunc DeleteTask(c *gin.Context) {
// Get model if exist
db := c.MustGet("db").(*gorm.DB)
var book models.Task
if err := db.Where("id = ?", c.Param("id")).First(&book).Error; err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Record not found!"})
return
}db.Delete(&book)c.JSON(http.StatusOK, gin.H{"data": true})}

Now we are ready to run our server and try out what we have created so far.

现在,我们准备运行服务器并尝试到目前为止所创建的内容。

Run

go run main.go

We can try to access the end point described in our main.go file. It must return required values.

我们可以尝试访问main.go文件中描述的终点。 它必须返回所需的值。

This is a very simple API example. By using this foundation, we can now continue creating more complex APIs.

这是一个非常简单的API示例。 通过使用此基础,我们现在可以继续创建更复杂的API。

Download repo here.

在此处下载回购。

翻译自: https://medium.com/wesionary-team/crud-api-using-go-d55b0ace211e

go-gin mysql

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值