1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
| package main
import ( "github.com/gin-gonic/gin" "gorm.io/driver/mysql" "gorm.io/gorm" "gorm.io/gorm/schema" "net/http" )
var DB *gorm.DB
func initMySQL() (err error) { dsn := "root:root@tcp(127.0.0.1:13306)/bubble?charset=utf8mb4&parseTime=True&loc=Local" DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{ NamingStrategy: schema.NamingStrategy{ SingularTable: true, }, }) if err != nil { return } return nil }
type Todo struct { ID int `json:"id"` Title string `json:"title"` Status bool `json:"status"` }
func main() { err := initMySQL() if err != nil { panic(err) } err = DB.AutoMigrate(&Todo{}) if err != nil { return }
r := gin.Default()
v1Group := r.Group("/v1") { v1Group.POST("/todo", func(c *gin.Context) { var todo Todo if err = c.ShouldBindJSON(&todo); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) } if err = DB.Create(&todo).Error; err != nil { c.JSON(http.StatusOK, gin.H{"error": err.Error()}) return } else { 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()}) return } else { c.JSON(http.StatusOK, gin.H{"data": todoList}) } }) v1Group.GET("/todo/:id", func(c *gin.Context) { var todo Todo if err = DB.First(&todo, c.Param("id")).Error; err != nil { c.JSON(http.StatusOK, gin.H{"error": err.Error()}) return } else { c.JSON(http.StatusOK, gin.H{"data": todo}) } }) v1Group.PUT("/todo/:id", func(c *gin.Context) { id, ok := c.Params.Get("id") if !ok { c.JSON(http.StatusOK, gin.H{"error": "无效的id"}) } 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.ShouldBindJSON(&todo) if err = DB.Save(&todo).Error; err != nil { c.JSON(http.StatusOK, gin.H{"error": err.Error()}) return } else { c.JSON(http.StatusOK, gin.H{"data": todo}) } }) v1Group.DELETE("/todo/:id", func(c *gin.Context) { var todo Todo id, ok := c.Params.Get("id") if !ok { c.JSON(http.StatusOK, gin.H{"error": "无效的id"}) } if err = DB.Where("id = ?", id).Delete(&Todo{}).Error; err != nil { c.JSON(http.StatusOK, gin.H{"error": err.Error()}) return } else { c.JSON(http.StatusOK, gin.H{"data": todo}) }
}) }
err = r.Run(":8080") if err != nil { return } }
|