使用 Gin 开发博客教程二

我们这节就来实现创建文章,涉及的要点创建数据表,ORM,创建文章。

建表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# 分类表
CREATE TABLE `category` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20),
`status` tinyint(3) unsigned NOT NULL DEFAULT 1,
PRIMARY KEY (`id`),
KEY `idx_name` (`name`)
) ENGINE=InnoDB;

# 文章表
CREATE TABLE `posts` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(200) NOT NULL,
`category_id` int(10) unsigned NOT NULL DEFAULT '0',
`content` text NOT NULL,
`is_top` int(10) unsigned NOT NULL DEFAULT '0',
`hits` int(10) unsigned NOT NULL DEFAULT '0',
`sorts` int(10) unsigned NOT NULL DEFAULT '0',
`status` tinyint(3) unsigned NOT NULL DEFAULT '0',
`created_at` timestamp,
`updated_at` timestamp,
PRIMARY KEY (`id`),
KEY `idx_title` (`title`),
KEY `idx_category_id` (`category_id`),
KEY `idx_sorts` (`sorts`)
) ENGINE=InnoDB;

选择ORM

我这里选择的 ORMgorm,安装方法为 go get -u github.com/jinzhu/gorm

1
2
3
4
5
6
7
func GetDB() *gorm.DB {
db, err := gorm.Open("mysql", "go:123456@/video?charset=utf8&parseTime=True&loc=Local")
if err != nil {
panic("failed to connect database")
}
return db
}

创建模板

1
router.LoadHTMLGlob("views/**/*")

建立目录 views,创建 create.html 表单模板,这里就写一个简单的模板文件就行。

1
2
3
4
5
6
7
8
9
10
11
12
13
<form action="/posts/store" method="post">
<div>
标题:
<input type="text" name="title">
</div>
<div>
内容:
<input type="text" name="title">
</div>
<div>
<input type="submit" value="提交" >
</div>
</form>

注册路由

1
2
router.GET("/posts/create", PostCreate)
router.POST("/posts/store", PostStore)

创建方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
func PostCreate(c *gin.Context) {
c.HTML(http.StatusOK, "create.html", nil)
}

func PostStore(c *gin.Context) {
title := c.PostForm("title")
content := c.PostForm("content")
ret := SavePost(title, content)
if ret {
c.String(http.StatusOk, "success")
} else {
c.String(http.StatusOk, "error")
}
}

创建入库

1
2
3
4
5
6
7
8
type Posts struct {
Title string
Content string
}
func SavePost(title, content string) bool {
posts := Posts{Title: title, Content: content}
return db.Create(&posts)
}
坚持原创技术分享,您的支持将鼓励我继续创作!
Flyertutor WeChat Pay

WeChat Pay

Flyertutor Alipay

Alipay