核心代码
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"net/http"
"time"
)
type Product struct {
Id int `gorm:"primaryKey;autoIncrement" json:"id"`
Number string `gorm:"unique" json:"number"`
Category string `gorm:"type:varchar(255);not null json:"category"`
Name string `gorm:"type:varchar(20);not null" json:"name"`
MadeIn string `gorm:"type:varchar(128);not null" json:"made_in"`
ProductionTime time.Time `json:"production_time"`
}
var gormDB * gorm.DB
func init() {
var err error
dsn := "golang:golang@tcp(127.0.0.1:3306)/golang?charset=utf8mb4&parseTime=True&loc=Local"
gormDB, err= gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
fmt.Println("连接数据库出错:",err.Error())
return
}
}
func main() {
r:= gin.Default()
r.POST("/insert",insertData)
r.GET("/get",get)
r.GET("/getMult",getMult)
r.PUT("/update",update)
r.DELETE("/delete",delete1)
r.Run()
}
func delete1(c *gin.Context) {
catchException(c)
id := c.Query("id")
tx := gormDB.Where("id=?", id).Delete(&Product{})
if tx.RowsAffected > 0 {
c.JSON(http.StatusBadGateway,gin.H{
"code":http.StatusOK,
"msg":"删除成功",
"data":"ok",
})
return
}else{
c.JSON(http.StatusBadGateway,gin.H{
"code":http.StatusBadGateway,
"msg":"删除失败",
"data":tx.Error,
})
}
return
}
func update(c *gin.Context) {
catchException(c)
var p Product
err := c.Bind(&p)
if err != nil {
c.JSON(http.StatusBadGateway,gin.H{
"code":http.StatusBadGateway,
"msg":"参数错误",
"data":err,
})
return
}
fmt.Println(p)
updates := gormDB.Where("name=?", p.Name).Updates(&p)
if updates.RowsAffected > 0 {
c.JSON(http.StatusBadGateway,gin.H{
"code":http.StatusOK,
"msg":"更新成功",
"data":"ok",
})
return
}else {
c.JSON(http.StatusBadGateway,gin.H{
"code":http.StatusOK,
"msg":"更新失败",
"data":updates.Error,
})
return
}
}
func getMult(c *gin.Context) {
catchException(c)
category := c.Query("category")
product := make([]Product,10)
tx := gormDB.Where("category=?", category).Find(&product).Limit(10)
if tx.Error != nil {
c.JSON(http.StatusOK,gin.H{
"code":http.StatusBadGateway,
"msg":"error",
"data":tx.Error,
})
return
}
c.JSON(http.StatusOK,gin.H{
"code":http.StatusOK,
"msg":"success",
"data":product,
})
return
}
func get(c *gin.Context) {
catchException(c)
var product Product
name := c.Query("name")
gormDB.Where("name=?", name).First(&product)
c.JSON(http.StatusOK,gin.H{
"code":http.StatusOK,
"msg":"success",
"data":product,
})
return
}
func insertData(c *gin.Context) {
catchException(c)
var p Product
err := c.Bind(&p)
if err != nil {
c.JSON(http.StatusBadGateway,gin.H{
"code":http.StatusBadGateway,
"msg":"参数错误",
"data":err,
})
return
}
create := gormDB.Create(&p)
if create.RowsAffected > 0 {
c.JSON(http.StatusBadGateway,gin.H{
"code":http.StatusOK,
"msg":"添加成功",
"data":true,
})
return
}
}
func catchException(c *gin.Context){
defer func() {
err := recover()
if err != nil {
c.JSON(http.StatusBadGateway,gin.H{
"code":http.StatusBadGateway,
"msg":err,
"data":err,
})
}
}()
}