设计Blog的后台的数据库
在 models中添加 blog.go,并添加博客中需要的各种字段
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封装
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);
前端
$('#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中的数据
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 核心代码
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)
作者:CoderMiner
链接:https://www.jianshu.com/p/3d425d1a39df
随时随地看视频