1 写文章功能开发
1)数据库设计
util添加article表操作:
//创建文章表
func CreateTableWithArticle(){
sql:=`create table if not exists article(
id int(4) primary key auto_increment not null,
title varchar(30),
author varchar(20),
tags varchar(30),
short varchar(255),
content longtext,
createtime int(10)
);`
ModifyDB(sql)
}
2)model层
3)控制层
4)路由层
beego.Router("/article/add", &controllers.AddArticleController{})
5)视图层
6)js
看一下初步的效果:
2 文章展示
2.1 首页展示
1)home_controller.go文件,在Get()方法中,先查询所有的文章,并显示到页面上。
func (this *HomeController) Get() {
page, _ := this.GetInt("page")
if page <= 0 {
page = 1
}
var artList []models.Article
artList, _ = models.FindArticleWithPage(page)
this.Data["PageCode"] = 1
this.Data["HasFooter"] = true
fmt.Println("IsLogin:", this.IsLogin, this.Loginuser)
this.Data["Content"] = models.MakeHomeBlocks(artList, this.IsLogin)
this.TplName = "home.html"
}
2)article_model.go文件中,添加文章的查询
//根据页码查询文章
func FindArticleWithPage(page int) ([]Article, error) {
//从配置文件中获取每页的文章数量
num, _ := beego.AppConfig.Int("articleListPageNum")
page--
fmt.Println("---------->page", page)
return QueryArticleWithPage(page, num)
}
/**
分页查询数据库
limit分页查询语句,
语法:limit m,n
m代表从多少位开始获取,与id值无关
n代表获取多少条数据
注意limit前面咩有where
*/
func QueryArticleWithPage(page, num int) ([]Article, error) {
sql := fmt.Sprintf("limit %d,%d", page*num, num)
return QueryArticlesWithCon(sql)
}
func QueryArticlesWithCon(sql string) ([]Article, error) {
sql = "select id,title,tags,short,content,author,createtime from article " + sql
rows, err := utils.QueryDB(sql)
if err != nil {
return nil, err
}
var artList []Article
for rows.Next() {
id := 0
title := ""
tags := ""
short := ""
content := ""
author := ""
var createtime int64
createtime = 0
rows.Scan(&id, &title, &tags, &short, &content, &author, &createtime)
art := Article{id, title, tags, short, content, author, createtime}
artList = append(artList, art)
}
return artList, nil
}
3)创建home_module.go进行首页文章展示
//----------首页显示内容---------
func MakeHomeBlocks(articles []Article, isLogin bool) template.HTML {
htmlHome := ""
for _, art := range articles {
//将数据库model转换为首页模板所需要的model
homeParam := HomeBlockParam{}
homeParam.Id = art.Id
homeParam.Title = art.Title
homeParam.Tags = createTagsLinks(art.Tags)
fmt.Println("tag-->", art.Tags)
homeParam.Short = art.Short
homeParam.Content = art.Content
homeParam.Author = art.Author
var timeLayoutStr = "2006-01-02 15:04:05"
homeParam.CreateTime = time.Unix(art.Createtime,0).Format(timeLayoutStr)
homeParam.Link = "/article/" + strconv.Itoa(art.Id)
homeParam.UpdateLink = "/article/update?id=" + strconv.Itoa(art.Id)
homeParam.DeleteLink = "/article/delete?id=" + strconv.Itoa(art.Id)
homeParam.IsLogin = isLogin
//处理变量
//ParseFile解析该文件,用于插入变量
t, _ := template.ParseFiles("views/block/home_block.html")
buffer := bytes.Buffer{}
//就是将html文件里面的比那两替换为穿进去的数据
t.Execute(&buffer, homeParam)
htmlHome += buffer.String()
}
return template.HTML(htmlHome)
}
//将tags字符串转化成首页模板所需要的数据结构
func createTagsLinks(tags string) []TagLink {
var tagLink [] TagLink
tagsPamar := strings.Split(tags, "&")
for _, tag := range tagsPamar {
tagLink = append(tagLink, TagLink{tag, "/?tag=" + tag})
}
return tagLink
}
4)视图层
在model的MakeHomeBlocks()方法中,就是需要使用模板填充格式化html页面内容,所以我们在views/block下再创建一个html页面:home_block.html
5)效果展示
2.2 分页展示
1)home_module设计
分页结构体对象
type HomeFooterPageCode struct {
HasPre bool
HasNext bool
ShowPage string
PreLink string
NextLink string
}
//-----------翻页-----------
//page是当前的页数
func ConfigHomeFooterPageCode(page int) HomeFooterPageCode {
pageCode := HomeFooterPageCode{}
//查询出总的条数
num := GetArticleRowsNum()
//从配置文件中读取每页显示的条数
pageRow, _ := beego.AppConfig.Int("articleListPageNum")
//计算出总页数
allPageNum := (num-1)/pageRow + 1
pageCode.ShowPage = fmt.Sprintf("%d/%d", page, allPageNum)
//当前页数小于等于1,那么上一页的按钮不能点击
if page <= 1 {
pageCode.HasPre = false
} else {
pageCode.HasPre = true
}
//当前页数大于等于总页数,那么下一页的按钮不能点击
if page >= allPageNum {
pageCode.HasNext = false
} else {
pageCode.HasNext = true
}
pageCode.PreLink = "/?page=" + strconv.Itoa(page-1)
pageCode.NextLink = "/?page=" + strconv.Itoa(page+1)
return pageCode
}
2)article_model.go文件中,加入查询总数据量的方法
还要考虑一个问题,就是当新增或删除文章的时候,数据总量会发生改变,所以还要修改增加文章的方法
3)home_controller.go
4)home.html
5)效果
2.3 展示文章详情
1)路由添加
2)show_article_controller.go
3)article_model.go文件中,添加方法,根据id查询文章
//----------查询文章-------------
func QueryArticleWithId(id int) Article {
row := utils.QueryRowDB("select id,title,tags,short,content,author,createtime from article where id=" + strconv.Itoa(id))
title := ""
tags := ""
short := ""
content := ""
author := ""
var createtime int64
createtime = 0
row.Scan(&id, &title, &tags, &short, &content, &author, &createtime)
art := Article{id, title, tags, short, content, author, createtime}
return art
}
4)在views目录下,新建html页面文件,show_article.html
2.4 修改文章
1)update_rticle_control.go
/**
* 更新文章的控制器
*/
type UpdateArticleController struct {
BaseController
}
//当访问/update路径的时候回触发Get()方法,响应的页面是通过TplName这个属性指定返回给客户端的页面
func (this *UpdateArticleController) Get() {
id, _ := this.GetInt("id")
fmt.Println(id)
//获取id所对应的文章信息
art := models.QueryArticleWithId(id)
this.Data["Title"] = art.Title
this.Data["Tags"] = art.Tags
this.Data["Short"] = art.Short
this.Data["Content"] = art.Content
this.Data["Id"] = art.Id
this.TplName = "write_article.html"
}
//修改文章
func (this *UpdateArticleController) Post() {
id, _ := this.GetInt("id")
fmt.Println("postid:", id)
//获取浏览器传输的数据,通过表单的name属性获取值
title := this.GetString("title")
tags := this.GetString("tags")
short := this.GetString("short")
content := this.GetString("content")
//实例化model,修改数据库
art := models.Article{id, title, tags, short, content, "", 0}
_, err := models.UpdateArticle(art)
//返回数据给浏览器
if err == nil {
this.Data["json"] = map[string]interface{}{"code": 1, "message": "更新成功"}
} else {
this.Data["json"] = map[string]interface{}{"code": 0, "message": "更新失败"}
}
this.ServeJSON()
}
2)write_article.html
<div id="main">
<form id="write-art-form" method="post">
<div>标题</div>
<input type="text" placeholder="请输入标题" name="title" value="{{.Title}}">
<div>标签</div>
<input type="text" placeholder="请输入标签" name="tags" value="{{.Tags}}">
<div>简介</div>
<textarea placeholder="请输入简介" name="short">{{.Short}}</textarea>
<div>内容</div>
<textarea id="content" placeholder="请输入内容" name="content">{{.Content}}</textarea>
<input id="write-article-id" hidden name="id" value="{{.Id}}">
<button type="button" onclick="history.back()">返回</button>
<button type="submit" id="write-art-submit">提交</button>
</form>
</div>
修改还是添加,其实要看页面上id的值,如果是添加使用默认值0,如果是修改是从数据库中查询出的真实数值,所以需要修改js脚本文件:
3)model层添加修改文章数据库操作
//----------修改数据----------
func UpdateArticle(article Article) (int64, error) {
//数据库操作
return utils.ModifyDB("update article set title=?,tags=?,short=?,content=? where id=?",
article.Title, article.Tags, article.Short, article.Content, article.Id)
}
3 标签开发
1)在article_model.go文件中查询数据库中存在的所有标签
2)创建tags_model.go
3)创建tags_controller.go
4)路由设置
beego.Router("/tags", &controllers.TagsController{})
5)视图层添加tags.html
6)tags效果展示