package api import ( "fmt" "github.com/gin-gonic/gin" db "main.go/database" "main.go/tools" . "main.go/type" ) // GetAllNotices 获取所有的公告 func GetAllNotices(c *gin.Context) { var notices []Notice if err := getAllNotices(¬ices); err != nil { c.JSON(200, gin.H{"code": 400, "msg": "Get all notices failure!"}) return } c.JSON(200, gin.H{"code": 200, "data": notices}) } func getAllNotices(notices *[]Notice) error { Link() DB := db.DBsnctf command := "SELECT id, title, content, created_at FROM notice ORDER BY created_at ASC;" rows, err := DB.Raw(command).Rows() if err != nil { return err } defer rows.Close() for rows.Next() { var b Notice err = rows.Scan(&b.ID, &b.Title, &b.Content, &b.CreatedAt) if err != nil { return err } *notices = append(*notices, b) } return rows.Err() } // AddNewNotices 新增公告 func AddNewNotices(c *gin.Context) { Link() DB := db.DBsnctf var request NoticeRequest if err := c.ShouldBindJSON(&request); err != nil { fmt.Println(err) c.JSON(400, gin.H{"code": 400, "msg": "Request format wrong!"}) return } addtime := tools.Timestamp() notice := &Notice{ Title: request.Title, Content: request.Content, CreatedAt: addtime, } err := DB.Table("notice").Create(¬ice).Error if err != nil { c.JSON(400, gin.H{"code": 400, "msg": "error for database"}) return } c.JSON(200, gin.H{"code": 200, "msg": "success!"}) } // DelNotice 删除公告 func DelNotice(c *gin.Context) { Link() DB := db.DBsnctf noticeid := c.Param("id") err := DB.Table("notice").Where("id = ?", noticeid).Delete(&Notice{}).Error if err != nil { c.JSON(400, gin.H{"code": 400, "msg": "error for database"}) return } c.JSON(200, gin.H{"code": 200, "msg": "success!"}) }