使用beego框架开发我的博客(二)

设计Blog的后台的数据库

在 models中添加 blog.go,并添加博客中须要的各类字段html

type BlogModel struct {
	Id       string     `bson:"_id"`
	Title    string     `bson:"title"`
	Summary  string     `bson:"summary"`
	Original string     `bson:"original"` //原始的markdown格式文本
	Content  string     `bson:"content"`  //渲染以后的html文本
	Date     time.Time  `bson:"date"`
	Tags     []TagModel `bson:"tags"`
}

type TagModel struct {
	Id   string `bson:"_id"`
	Name string `bson:"name"`
}
复制代码

使用MongoDB的Go驱动mgo,封装相关的方法

单首创建一个文件夹 db,并添加 mongodb.go,经常使用的CRUD的封装,核心代码前端

  • 获取 Session
var globalS *mgo.Session

func init() {
	dialInfo := &mgo.DialInfo{
		Addrs:     []string{host},
		Timeout:   timeout,
		Source:    authdb,
		Username:  user,
		Password:  pass,
		PoolLimit: poollimit,
	}
	s, err := mgo.DialWithInfo(dialInfo)
	if err != nil {
		log.Fatal("create session error", err)
	}
	globalS = s
}
复制代码
  • 链接,CURD封装

具体的封装的代码请参考 mgo CRUD封装git

func connect(db, collection string) (*mgo.Session, *mgo.Collection) {
	ms := globalS.Copy()
	c := ms.DB(db).C(collection)
	return ms, c
}

func Insert(db, collection string, docs ...interface{}) error {
	ms, c := connect(db, collection)
	defer ms.Close()
	return c.Insert(docs...)
}

......

复制代码

先后台交互

前端使用 ajaxPOST数据到后台,beego能够提供了一些方法获取request中的数据 请求而数据处理 请自行查看,核心代码
获取原始markdown数据方法 var origin = simplemde.value();,获取渲染后的html格式的内容方法 var content = simplemde.markdown(origin);github

  • 前端
$('#submit').click(function(){
		var title = $("#blog-title").val();
		var origin = simplemde.value();
		var content = simplemde.markdown(origin);
		if(title.length == 0){
				$('#alert').show();
				$('#alert').text("请输入标题信息");
				setTimeout(function(){
						$("#alert").hide();  
				},2000)
		}
		if(origin.length == 0){
				$('#alert').show();
				$('#alert').text("请输入具体的博客内容");
				setTimeout(function(){
						$("#alert").hide();  
				},2000)
		}

		$.ajax({
				url:'/editor',
				method:'POST',
				data:{title:title,origin:origin,content:content},
				success:function(data){
						alert(data)
				}
		})

})
复制代码
  • 后端

使用 GetString()方法获取Request中的数据ajax

func (this *EditorController) Post() {
	title := this.GetString("title")
	origin := this.GetString("origin")
	content := this.GetString("content")
	fmt.Println("post data", title, origin, content)

	this.ServeJSON()
}
复制代码

提交内容到数据库

model 核心代码mongodb

const (
	database   = "Blog"
	collection = "BlogModel"
)

func (b *BlogModel) PostBlog(blog *BlogModel) error {
	return db.Insert(database, collection, blog)
}
复制代码

controller 核心代码数据库

blog := &models.BlogModel{
	Id:       bson.NewObjectId().Hex(),
	Title:    title,
	Original: origin,
	Content:  content,
	Date:     time.Now(),
}

blog.PostBlog(blog)
复制代码

完整源码后端

测试效果图bash

编辑器
数据库
相关文章
相关标签/搜索