gin框架项目 待办清单

Go web开发系列教程,基于Gin框架和GORM的练手小项目。

源码地址:https://github.com/Q1mi/bubble

package main

import (
	"github.com/gin-gonic/gin"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"net/http"
)

type  Todo struct {
	ID int `json:"id"`
	Title string `json:"title"`
	Status bool `json:"status"`

}

var(
	DB *gorm.DB
)

func initMysql() (err error){
	dsn := "bubble_name:bubble_passwd@tcp(127.0.0.1:3306)/bubble?charset=utf8mb4&parseTime=True&loc=Local"
	DB,err=gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err !=nil{
		return
	}
	return
}
func main(){
	//创建数据库
	err:=initMysql()
	if err !=nil{
		panic(err)
	}
	defer func() {
		sqlDb,err:=DB.DB()
		if err!=nil{
			return
		}
		sqlDb.Close()
	}()
	DB.AutoMigrate(&Todo{})
	//连接数据库

	r:=gin.Default()
	r.Static("/static","static")
	r.LoadHTMLGlob("templates/*")
	r.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK,"index.html",nil)
	})

	//代办事项

	v1Group:=r.Group("v1")
	{
		//添加
		v1Group.POST("/todo", func(c *gin.Context) {
			//get requests
			var todo Todo
			c.BindJSON(&todo)
			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{
				//	"data":todo,
				//})
			}


		})
		//查看
		v1Group.GET("/todo", func(c *gin.Context) {
			var todoList []Todo
			if err =DB.Find(&todoList).Error;err !=nil{
				c.JSON(http.StatusOK,gin.H{"error":err.Error()})

			}else {
				c.JSON(http.StatusOK,todoList)
			}


		})

		v1Group.GET("/todo/:id", func(c *gin.Context) {


		})

		//修改

		v1Group.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
			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)
			}
		})

		//删除

		v1Group.DELETE("/todo/:id", func(c *gin.Context) {
			id,ok:=c.Params.Get("id")
			if !ok{
				c.JSON(http.StatusOK,gin.H{"error":"无效id"})
				return
			}

			err=DB.Where("id=?",id).Delete(Todo{}).Error
			if err != nil {
				c.JSON(http.StatusOK,gin.H{"err":err.Error()})
			}else {
				c.JSON(http.StatusOK,gin.H{id:"delete"})
			}


		})


	}


	r.Run()

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值