gin framework CRUD small chestnuts

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"net/http"
)

type Todo struct {
	ID int `json:"id"`  //和前端做交互 使用的是json数据
	Title string `json:"title"`
	Status bool	`json:"status"`
}

func initMySQL()(err error)  {
	dsn := "root:123456@(xxxxx:3306)/database_name?charset=utf8&parseTime=True&loc=Local"
	db, err  := gorm.Open("mysql", dsn)
	if err!= nil{
		panic(err)
	}
	return db.DB().Ping()
}

// 遇事不决 注释先行
func main() {

	//err := initMySQL()
	//if err!= nil{
	//	panic(err)
	//}

	//1. 连接MySql数据库
	db, err  := gorm.Open("mysql", "root:123456@(xxxxxx/gormDemo?charset=utf8&parseTime=True&loc=Local")
	if err!= nil{
		panic(err)
	}
	defer db.Close()

	//2. 自动迁移  把结构体和数据表进行对应
	db.AutoMigrate(&Todo{})

	r := gin.Default()
	//声明 模板文件引用的静态文件去哪找  以/static 访问的请求 到static目录下找静态文件
	r.Static("/static", "static")

	// 告诉gin框架去哪里找index.html
	r.LoadHTMLGlob("templates/*")

	r.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", nil)
	})

	//route1
	route1Group := r.Group("v1")
	{
		//待办事项
		//添加
		route1Group.POST("/todo", func(c *gin.Context) {

			// 1.请求中取数据
			var todo Todo
			c.BindJSON(&todo)

			// 2.存储数据
			//err = db.Create(&todo).Error
			//if err != nil {  这几行简写为下面的格式
			//
			//}

			//2.存储数据 3.返回响应
			if err = db.Create(&todo).Error; err != nil {
				c.JSON(http.StatusOK, gin.H{"error": err.Error()})
			}else {
				c.JSON(http.StatusOK, todo)
				/*统一响应格式c.JSON(http.StatusOK, gin.H{
									"code": 2000,
									"msg": "success",
									"data": todo,
				})*/
			}

			t1 := Todo{ID: 2, Title: "native", Status:true}
			db.Create(&t1)
		})

		//find all
		route1Group.GET("/todo", func(c *gin.Context) {
			var todoList []Todo
			err = db.Find(&todoList).Error
			if err != nil {
				c.JSON(http.StatusOK, gin.H{"error": err.Error()})
			}else {
				c.JSON(http.StatusOK, todoList)
			}
		})

		// find one
		route1Group.GET("/todo/:id", func(c *gin.Context) {
			var t = new(Todo)
			db.First(t)
			fmt.Printf("%#v\n", t)
		})

		//修改  某一个
		route1Group.PUT("/todo/:id", func(c *gin.Context) {
			id, ok := c.Params.Get("id")  //获取请求参数
			if !ok {
				c.JSON(http.StatusOK, gin.H{"error": "id不存在"})
				return
			}
			var todo Todo
			// 根据id查询待修改实体
			if err = db.Where("id=?", id).First(&todo).Error; err != nil{
				c.JSON(http.StatusOK,gin.H{"error": err.Error()})
				return
			}
			c.BindJSON(&todo)
			if err = db.Save(&todo).Error; err != nil{
				c.JSON(http.StatusOK, gin.H{"error": err.Error()})
			}else {
				c.JSON(http.StatusOK, todo)
			}


		})

		//删除 某一个
		route1Group.DELETE("/todo/:id", func(c *gin.Context) {
			id, ok := c.Params.Get("id")
			if !ok {
				c.JSON(http.StatusOK, gin.H{"error":"无效的id"})
				return
			}
			if err = db.Where("id=?", id).Delete(Todo{}).Error; err!=nil{
				c.JSON(http.StatusOK,gin.H{"error": err.Error()})
			}else {
				c.JSON(http.StatusOK, gin.H{id: "deleted"})
			}
		})
	}

	r.Run()

}
Published 100 original articles · won praise 15 · views 40000 +

Guess you like

Origin blog.csdn.net/qq_37767455/article/details/104778670