使用beego框架開發我的博客(三)

上篇文章已經能夠提交文章到數據庫,須要在Post時,改造一下返回結果,若是提交成功就跳轉 到文章列表頁面,若是提交失敗就顯示提示信息html

封裝POST返回結果

添加一個輔助的方法,來封裝response前端

package utils

import (
	"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)
	}
}

複製代碼

在提交時,若是失敗返回對應的錯誤碼和錯誤信息git

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",
  }
}
複製代碼

前端頁面邏輯github

$.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 和路由ajax

  • controller blog.go
package controllers

import "github.com/astaxie/beego"

type BlogController struct {
	beego.Controller
}

func (this *BlogController) Get() {
	this.TplName = "index.html"
}
複製代碼
  • 路由
beego.Router("/blog", &controllers.BlogController{})
複製代碼
  • 列表頁面

效果圖

從數據庫中查詢全部的數據數據庫

modelsjson

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

controllersbash

func (this *BlogController) Get() {
	blogs, err := models.NewBlog().GetAllBlogs(0)
	if err == nil {
		this.Data["Blogs"] = blogs
	}

	this.TplName = "index.html"
}
複製代碼
  • 頁面渲染

index.htmlmarkdown

{{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}}
複製代碼
  • 詳情頁面

效果圖

modelspost

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>
複製代碼

完整的源碼

相關文章
相關標籤/搜索