{% raw %}
# 13.5 實現博客的增刪改
前面介紹了beego框架實現的整體構思以及部分實現的偽代碼,這小節介紹通過beego建立一個博客系統,包括博客瀏覽、添加、修改、刪除等操作。
## 博客目錄
博客目錄如下所示:
.
├── controllers
│?? ├── delete.go
│?? ├── edit.go
│?? ├── index.go
│?? ├── new.go
│?? └── view.go
├── main.go
├── models
│?? └── model.go
└── views
├── edit.tpl
├── index.tpl
├── layout.tpl
├── new.tpl
└── view.tpl
## 博客路由
博客主要的路由規則如下所示:
//顯示博客首頁
beego.Router("/", &controllers.IndexController{})
//查看博客詳細信息
beego.Router("/view/:id([0-9]+)", &controllers.ViewController{})
//新建博客博文
beego.Router("/new", &controllers.NewController{})
//刪除博文
beego.Router("/delete/:id([0-9]+)", &controllers.DeleteController{})
//編輯博文
beego.Router("/edit/:id([0-9]+)", &controllers.EditController{})
## 數據庫結構
數據庫設計最簡單的博客信息
CREATE TABLE entries (
id INT AUTO_INCREMENT,
title TEXT,
content TEXT,
created DATETIME,
primary key (id)
);
## 控制器
IndexController:
type IndexController struct {
beego.Controller
}
func (this *IndexController) Get() {
this.Data["blogs"] = models.GetAll()
this.Layout = "layout.tpl"
this.TplNames = "index.tpl"
}
ViewController:
type ViewController struct {
beego.Controller
}
func (this *ViewController) Get() {
id, _ := strconv.Atoi(this.Ctx.Input.Params[":id"])
this.Data["Post"] = models.GetBlog(id)
this.Layout = "layout.tpl"
this.TplNames = "view.tpl"
}
NewController
type NewController struct {
beego.Controller
}
func (this *NewController) Get() {
this.Layout = "layout.tpl"
this.TplNames = "new.tpl"
}
func (this *NewController) Post() {
inputs := this.Input()
var blog models.Blog
blog.Title = inputs.Get("title")
blog.Content = inputs.Get("content")
blog.Created = time.Now()
models.SaveBlog(blog)
this.Ctx.Redirect(302, "/")
}
EditController
type EditController struct {
beego.Controller
}
func (this *EditController) Get() {
id, _ := strconv.Atoi(this.Ctx.Input.Params[":id"])
this.Data["Post"] = models.GetBlog(id)
this.Layout = "layout.tpl"
this.TplNames = "edit.tpl"
}
func (this *EditController) Post() {
inputs := this.Input()
var blog models.Blog
blog.Id, _ = strconv.Atoi(inputs.Get("id"))
blog.Title = inputs.Get("title")
blog.Content = inputs.Get("content")
blog.Created = time.Now()
models.SaveBlog(blog)
this.Ctx.Redirect(302, "/")
}
DeleteController
type DeleteController struct {
beego.Controller
}
func (this *DeleteController) Get() {
id, _ := strconv.Atoi(this.Ctx.Input.Params[":id"])
blog := models.GetBlog(id)
this.Data["Post"] = blog
models.DelBlog(blog)
this.Ctx.Redirect(302, "/")
}
## model層
package models
import (
"database/sql"
"github.com/astaxie/beedb"
_ "github.com/ziutek/mymysql/godrv"
"time"
)
type Blog struct {
Id int `PK`
Title string
Content string
Created time.Time
}
func GetLink() beedb.Model {
db, err := sql.Open("mymysql", "blog/astaxie/123456")
if err != nil {
panic(err)
}
orm := beedb.New(db)
return orm
}
func GetAll() (blogs []Blog) {
db := GetLink()
db.FindAll(&blogs)
return
}
func GetBlog(id int) (blog Blog) {
db := GetLink()
db.Where("id=?", id).Find(&blog)
return
}
func SaveBlog(blog Blog) (bg Blog) {
db := GetLink()
db.Save(&blog)
return bg
}
func DelBlog(blog Blog) {
db := GetLink()
db.Delete(&blog)
return
}
## view層
layout.tpl
<html>
<head>
<title>My Blog</title>
<style>
#menu {
width: 200px;
float: right;
}
</style>
</head>
<body>
<ul id="menu">
<li><a href="/">Home</a></li>
<li><a href="/new">New Post</a></li>
</ul>
{{.LayoutContent}}
</body>
</html>
index.tpl
<h1>Blog posts</h1>
<ul>
{{range .blogs}}
<li>
<a href="/view/{{.Id}}">{{.Title}}</a>
from {{.Created}}
<a href="/edit/{{.Id}}">Edit</a>
<a href="/delete/{{.Id}}">Delete</a>
</li>
{{end}}
</ul>
view.tpl
<h1>{{.Post.Title}}</h1>
{{.Post.Created}}<br/>
{{.Post.Content}}
new.tpl
<h1>New Blog Post</h1>
<form action="" method="post">
標題:<input type="text" name="title"><br>
內容:<textarea name="content" colspan="3" rowspan="10"></textarea>
<input type="submit">
</form>
edit.tpl
<h1>Edit {{.Post.Title}}</h1>
<h1>New Blog Post</h1>
<form action="" method="post">
標題:<input type="text" name="title" value="{{.Post.Title}}"><br>
內容:<textarea name="content" colspan="3" rowspan="10">{{.Post.Content}}</textarea>
<input type="hidden" name="id" value="{{.Post.Id}}">
<input type="submit">
</form>
## links
* [目錄](<preface.md>)
* 上一章: [日志和配置設計](<13.4.md>)
* 下一節: [小結](<13.6.md>)
{% endraw %}
- 目錄
- Go環境配置
- Go安裝
- GOPATH 與工作空間
- Go 命令
- Go開發工具
- 小結
- Go語言基礎
- 你好,Go
- Go基礎
- 流程和函數
- struct
- 面向對象
- interface
- 并發
- 小結
- Web基礎
- web工作方式
- Go搭建一個簡單的web服務
- Go如何使得web工作
- Go的http包詳解
- 小結
- 表單
- 處理表單的輸入
- 驗證表單的輸入
- 預防跨站腳本
- 防止多次遞交表單
- 處理文件上傳
- 小結
- 訪問數據庫
- database/sql接口
- 使用MySQL數據庫
- 使用SQLite數據庫
- 使用PostgreSQL數據庫
- 使用beedb庫進行ORM開發
- NOSQL數據庫操作
- 小結
- session和數據存儲
- session和cookie
- Go如何使用session
- session存儲
- 預防session劫持
- 小結
- 文本文件處理
- XML處理
- JSON處理
- 正則處理
- 模板處理
- 文件操作
- 字符串處理
- 小結
- Web服務
- Socket編程
- WebSocket
- REST
- RPC
- 小結
- 安全與加密
- 預防CSRF攻擊
- 確保輸入過濾
- 避免XSS攻擊
- 避免SQL注入
- 存儲密碼
- 加密和解密數據
- 小結
- 國際化和本地化
- 設置默認地區
- 本地化資源
- 國際化站點
- 小結
- 錯誤處理,調試和測試
- 錯誤處理
- 使用GDB調試
- Go怎么寫測試用例
- 小結
- 部署與維護
- 應用日志
- 網站錯誤處理
- 應用部署
- 備份和恢復
- 小結
- 如何設計一個Web框架
- 項目規劃
- 自定義路由器設計
- controller設計
- 日志和配置設計
- 實現博客的增刪改
- 小結
- 擴展Web框架
- 靜態文件支持
- Session支持
- 表單支持
- 用戶認證
- 多語言支持
- pprof支持
- 小結
- 參考資料