//历史事件 type Story struct { // ID is story's id ID int`json:"id"` TimeStamp int64`json:"timeStamp"` Name string`json:"name"` StoryDescribe string`json:"storyDescribe"` }
数据库变量
1
var db *gorm.DB
main函数中初始化数据库
1 2 3 4 5 6
var err error db, err = gorm.Open("sqlite3", "./Wizz-Home-Page.Database") if err != nil { log.Fatal(err) } db.AutoMigrate(&Story{}) //数据库自动根据结构体建表
读取所有
1 2 3 4 5
funcReadStories(c *gin.Context) { var stories []Story db.Find(&stories) c.JSON(200, stories) }
读取单个
1 2 3 4 5 6 7 8 9 10
funcReadStory(c *gin.Context) { id := c.Params.ByName("id") var story Story db.First(&story, id) if story.ID == 0 { c.JSON(404, gin.H{"message": "Story not found"}) return } c.JSON(200, story) }
创建
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
funcCreateStory(c *gin.Context) { var story Story
if err := c.BindJSON(&story); err != nil { log.Println(err) c.JSON(400, "Not a Story") return }
if story.ID != 0 { c.JSON(400, gin.H{"message": "Pass id in body is not allowed"}) return } db.Create(&story) c.JSON(200, story) }
funcUpdateStory(c *gin.Context) { id, err := strconv.Atoi(c.Params.ByName("id")) if err != nil { c.JSON(400, gin.H{"message": "your id is not a number"}) return } var story Story db.First(&story, id) if story.ID == 0 { c.JSON(404, gin.H{"message": "Story not found"}) return } err = c.ShouldBindJSON(&story) if err != nil { log.Println(err) } if story.ID != id { c.JSON(400, gin.H{"message": "Pass id in body is not allowed"}) return } db.Save(&story) c.JSON(200, story) }
删除
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
funcDeleteStory(c *gin.Context) { id, err := strconv.Atoi(c.Params.ByName("id")) if err != nil { c.JSON(400, gin.H{"message": "your id is not a number"}) return } var story Story db.First(&story, id) if story.ID == 0 { c.JSON(404, gin.H{"message": "Story not found"}) return } db.Delete(&story) c.JSON(200, gin.H{"message": "delete success"}) }