在 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"`
}
复制代码
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
}
复制代码
具体的封装的代码请参考 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...)
}
......
复制代码
前端使用 ajax
POST数据到后台,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