为了账号安全,请及时绑定邮箱和手机立即绑定

使用beego框架开发个人博客(三)

标签:
Go

上篇文章已经可以提交文章到数据库,需要在Post时,改造一下返回结果,如果提交成功就跳转

到文章列表页面,如果提交失败就显示提示信息

封装POST返回结果

添加一个辅助的方法,来封装response

package utilsimport (    "encoding/json"
    "net/http")type Response struct {
    Status int    `json:"status"`
    Msg    string `json:"msg"`
}

func (resp *Response) WriteJson(w http.ResponseWriter) {
    data, err := json.Marshal(resp)    if err != nil {
        w.Write([]byte(`{Status:-1}`))
    } else {
        w.Write(data)
    }
}

在提交时,如果失败返回对应的错误码和错误信息

resp := utils.Response{
  Status: 0,
}
defer resp.WriteJson(this.Ctx.ResponseWriter)

err := blog.PostBlog(blog)if err != nil {
  resp = utils.Response{
    Status: -1,
    Msg:    "post blog error",
  }
}

前端页面逻辑

$.ajax({                    url:'/editor',                    method:'POST',                    data:{title:title,origin:origin,content:content},                    success:function(data){
                        alert(data)                        var resp = JSON.parse(data)                        if(resp.status == 0){                            window.location.href="/blog";
                        }else{
                            alert(JSON.parse(resp.msg))
                        }
                    }
                })

添加文章列表、详情页面

和之前的逻辑一样,添加对应的模板页面 index.html,添加对用的controller BlogController
和路由

  • controller blog.go

package controllersimport "github.com/astaxie/beego"type BlogController struct {
    beego.Controller
}

func (this *BlogController) Get() {    this.TplName = "index.html"}
  • 路由

beego.Router("/blog", &controllers.BlogController{})
  • 列表页面

https://img1.sycdn.imooc.com//5d5df65e0001ab6608710741.png

效果图

从数据库中查询所有的数据

models

func (b *BlogModel) GetAllBlogs(page int) ([]BlogModel, error) {
    var blogs []BlogModel
    err := db.FindAllSort(database, collection, "-date", nil, nil, &blogs)    return blogs, err
}

controllers

func (this *BlogController) Get() {
    blogs, err := models.NewBlog().GetAllBlogs(0)    if err == nil {        this.Data["Blogs"] = blogs
    }    this.TplName = "index.html"}
  • 页面渲染

index.html

{{range .Blogs}}<article class="post-card">
        <a class="post-card-image-link" href="/blog/{{.Id}}">
                {{if .Img}}                <div class="post-card-image" style="background-image: url({{.Img}})">

                </div>
                {{end}}        </a>
        <div class="post-card-content">
                <a class="post-card-content-link" href="">
                        <header class="post-card-header">
                                <span class="post-card-tags">Golang</span>

                                <h2 class="post-card-title">{{.Title}}</h2>
                        </header>
                        <section class="post-card-excerpt">
                                <p>
                                        {{.Summary}}                                </p>
                        </section>
                </a>
                <footer class="post-card-meta">
                        <span class="post-card-author">
                                <a href="https://github.com/coderminer">{{.Author}}</a>
                        </span>
                        <span class="post-card-date">{{dateformat .Date "2006年01月02日"}}</span>
                </footer>
        </div></article>{{end}}
  • 详情页面

https://img1.sycdn.imooc.com//5d5df6620001db0408850566.png

效果图

models

func (b *BlogModel) GetBlogById(id string) (BlogModel, error) {
    var blog BlogModel
    err := db.FindOne(database, collection, bson.M{"_id": id}, nil, &blog)    return blog, err
}

controllers

func (this *BlogController) Detail() {    id := this.Ctx.Input.Param(":id")
    data, err := models.NewBlog().GetBlogById(id)    if err == nil {        this.Data["Content"] = data
    } else {        this.Abort("404")
    }    this.TplName = "detail.html"}

routers

    beego.Router("/blog/:id", &controllers.BlogController{}, "get:Detail")

详情页面

<article class="post ">
                        <div class="post-head">
                            <h1 class="post-title">
                                {{.Content.Title}}                            </h1>
                            <div class="post-meta">
                                <span class="author">
                                    作者:                                    <a href="https://github.com/coderminer">{{.Content.Author}}</a>
                                </span>
                                <time class="post-date">{{dateformat .Content.Date "2006年01月02日"}}</time>
                            </div>
                        </div>

                        <div class="post-content markdown-body">
                            <p>{{str2html .Content.Content}}</p>
                        </div>

                        <footer class="post-footer clearfix">
                            <div class="pull-left tag-list">
                                <i class="fa fa-folder-open-o">
                                    {{range .Content.Tags}}                                    <a href="/blog/tag/{{.Id}}">{{.Name}}</a>
                                    {{end}}                                </i>
                            </div>
                        </footer>
                    </article>

完整的源码



作者:CoderMiner
链接:https://www.jianshu.com/p/bfba91045ad4

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 1
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消