7、更新文章
ru.PUT("/api/v1/post", api.API.UpdatePost)
func (*Api) UpdatePost(c *gin.Context) {
// post 更新
//获取用户id判断是否登录
token := c.Request.Header.Get("Authorization")
_, claim, err := utils.ParseToken(token)
if err != nil {
c.HTML(200, "writing.html", err)
return
}
uid := claim.Uid
var pv SaveP
c.ShouldBind(&pv)
// post save
cid, _ := strconv.Atoi(pv.CategoryId)
pidStr := c.Param("pid")
pid, err := strconv.Atoi(pidStr)
typeId, _ := strconv.Atoi(pv.Type)
post := &models.Post{
Pid: pid,
Title: pv.Title,
Slug: pv.Slug,
Content: pv.Content,
Markdown: pv.Markdown,
CategoryId: cid,
UserId: uid,
ViewCount: 0,
Type: typeId,
CreateAt: time.Now(),
UpdateAt: time.Now(),
}
service.UpdatePost(post)
c.JSON(200, gin.H{
"code": 200,
"error": "这里没错",
"data": post,
})
}
service.UpdatePost(post)
更新数据库中的内容:
func UpdatePost(post *models.Post) {
_, err := DB.Exec("UPDATE blog_post set title=? ,content=?,markdown=?,category_id=?,type=?,slug=?, update_at=? where user_id=?",
post.Title,
post.Content,
post.Markdown,
post.CategoryId,
post.Type,
post.Slug,
post.UpdateAt,
post.UserId,
)
if err != nil {
log.Println(err)
}
}
8、删除文章
ru.DELETE("/api/v1/post/:pid", api.API.DeletePost)
在js中可以看到,当在文章详情页面点击删除时,url将发生跳转,"/api/v1/post/:pid"
,不过请求类类型将转换为Delete请求:
func (*Api) DeletePost(c *gin.Context) {
pidStr := c.Param("pid")
pid, err := strconv.Atoi(pidStr)
if err != nil {
log.Println("获取文章pid失败")
return
}
dao.DeletePost(pid)
post, err := dao.GetAllPost()
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": -999,
"error": err,
"data": "",
})
return
}
c.JSON(http.StatusOK, gin.H{
"code": 200,
"error": "",
"data": post,
})
}
查看前端文件index.js,可知在删除后将发生跳转到主页面,需要返回code和data数据
将id对应的数据,在数据库中删除:
func DeletePost(pid int) {
_, err := DB.Exec("delete from blog_post where pid=? ", pid)
if err != nil {
log.Println(err)
return
}
}
9、归档功能
即按照月份进行文章的分类
//归档
ru.GET("/pigeonhole", views.Html.Pigeonhole)
返回html格式信息
func (*HTMLApi) Pigeonhole(c *gin.Context) {
pigeonholeRes := service.FindPostPigronhole()
c.HTML(200, "pigeonhole.html", pigeonholeRes)
}
func FindPostPigronhole() models.PigeonholeRes {
// 查询所有 按照月份分类
categorys, _ := dao.GetAllCategory()
posts, _ := dao.GetAllPost()
pigeonholeMap := make(map[string][]models.Post)
for _, post := range posts {
at := post.CreateAt
month := at.Format("2006-01")
pigeonholeMap[month] = append(pigeonholeMap[month], post)
}
return models.PigeonholeRes{
Viewer: config.Cfg.Viewer,
SystemConfig: config.Cfg.System,
Categorys: categorys,
Lines: pigeonholeMap,
}
}
归档返回函数的结构体:
type PigeonholeRes struct {
config.Viewer
config.SystemConfig
Categorys []Category
Lines map[string][]Post
}
本项目主体部分到此结束,后续会有项目如何在docker上的部署教程,源码GitHub连接:GitHub - Libing0804/gin_blog: gin框架搭建web_blog
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)