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()
}