完成第十三章的书写
This commit is contained in:
2
13.1.md
2
13.1.md
@@ -44,4 +44,4 @@ gopath是一个文件系统的目录,我们可以随便设置一个目录为go
|
||||
## links
|
||||
* [目录](<preface.md>)
|
||||
* 上一章: [构建博客系统](<13.md>)
|
||||
* 下一节: [数据库设计](<13.2.md>)
|
||||
* 下一节: [自定义路由器设计](<13.2.md>)
|
||||
568
13.2.md
568
13.2.md
@@ -1,308 +1,260 @@
|
||||
# 13.2 数据库设计
|
||||
我们设计的博客是一个单用户的博客,目前很多用户都采用wordpress作为自己的博客系统,包括我自己也在使用wordpress,我们知道wordpress系统的一个主页乐观的估计也有20余次查询,但这依然无法阻挡这款程序的流行,在去年对全球top10 blogger所使用的系统调查中,wordpress比其他系统有着明显的优势。
|
||||
|
||||
但是我们这次演示的博客系统是一个单用户的系统所以查询肯定不需要20余次,数据库的结构也相对的简单很多,因此单用户系统设计重点在于灵活性和结构化,当我们集中地暴露系统瓶颈,从另一个方面也可以集中精力去解决它。例如把数据库从MySQL改成redis。
|
||||
|
||||
博客主要分为博文、分类、页面、评论、用户、友情链接、tag,那么我们可以采用内容表存储一些实体相关的信息:文章内容、草稿、页面等信息,meta表保存分类、tag等信息,关系表维护两者的关系,评论表存储用户的评论,用户表存储博客用户的信息。
|
||||
|
||||
## 内容表
|
||||
这张表主要用来存储内容实体信息,主要的表结构如下所示
|
||||
|
||||
<table width="100%">
|
||||
<tr>
|
||||
<td>键名</td>
|
||||
<td>类型</td>
|
||||
<td>属性</td>
|
||||
<td>解释</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>cid</td>
|
||||
<td>int(10)</td>
|
||||
<td>主键,非负,自增</td>
|
||||
<td>post表主键</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>title</td>
|
||||
<td>varchar(200)</td>
|
||||
<td>可为空</td>
|
||||
<td>内容标题</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>slug</td>
|
||||
<td>varchar(200)</td>
|
||||
<td>索引,可为空</td>
|
||||
<td>内容缩略名</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>created</td>
|
||||
<td>int(10)</td>
|
||||
<td>索引,非负,可为空</td>
|
||||
<td>内容生成时的GMT unix时间戳</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>modified</td>
|
||||
<td>int(10)</td>
|
||||
<td>非负,可为空</td>
|
||||
<td>内容更改时的GMT unix时间戳</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>text</td>
|
||||
<td>text</td>
|
||||
<td>可为空</td>
|
||||
<td>内容文字</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>order</td>
|
||||
<td>int(10)</td>
|
||||
<td>非负,可为空</td>
|
||||
<td>排序</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>authorId</td>
|
||||
<td>int(10)</td>
|
||||
<td>非负,可为空</td>
|
||||
<td>内容所属用户id</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>type</td>
|
||||
<td>varchar(16)</td>
|
||||
<td>可为空</td>
|
||||
<td>内容类别</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>status</td>
|
||||
<td>varchar(16)</td>
|
||||
<td>可为空</td>
|
||||
<td>内容状态</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>password</td>
|
||||
<td>varchar(32)</td>
|
||||
<td>可为空</td>
|
||||
<td>受保护内容,此字段对应内容保护密码</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>commentsNum</td>
|
||||
<td>int(10)</td>
|
||||
<td>非负,可为空</td>
|
||||
<td>内容所属评论数,冗余字段</td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
|
||||
## 关系表
|
||||
这张表维护着内容表和扩展表之间的关系
|
||||
|
||||
<table width="100%">
|
||||
<tr>
|
||||
<td>键名</td>
|
||||
<td>类型</td>
|
||||
<td>属性</td>
|
||||
<td>解释</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>cid</td>
|
||||
<td>int(10)</td>
|
||||
<td>主键,非负</td>
|
||||
<td>内容主键</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>mid</td>
|
||||
<td>int(10)</td>
|
||||
<td>主键,非负</td>
|
||||
<td>扩展表主键</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## meta表
|
||||
这张表主要用来存储和内容相关联的一些扩展信息,包括tag、分类之类的信息
|
||||
|
||||
<table width="100%">
|
||||
<tr>
|
||||
<td>键名</td>
|
||||
<td>类型</td>
|
||||
<td>属性</td>
|
||||
<td>解释</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>mid</td>
|
||||
<td>int(10)</td>
|
||||
<td>主键,非负</td>
|
||||
<td>扩展表主键</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>name</td>
|
||||
<td>varchar(200)</td>
|
||||
<td>可为空</td>
|
||||
<td>名称</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>slug</td>
|
||||
<td>varchar(200)</td>
|
||||
<td>索引,可为空</td>
|
||||
<td>扩展缩略名</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>type</td>
|
||||
<td>varchar(32)</td>
|
||||
<td>可为空</td>
|
||||
<td>扩展类型</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>description</td>
|
||||
<td>varchar(200)</td>
|
||||
<td>可为空</td>
|
||||
<td>扩展描述</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>count</td>
|
||||
<td>int(10)</td>
|
||||
<td>非负,可为空</td>
|
||||
<td>扩展所属内容个数,冗余字段</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>order</td>
|
||||
<td>int(10)</td>
|
||||
<td>非负,可为空</td>
|
||||
<td>扩展排序</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
|
||||
## 评论表
|
||||
实体内容表相应的评论信息表
|
||||
|
||||
|
||||
<table width="100%">
|
||||
<tr>
|
||||
<td>键名</td>
|
||||
<td>类型</td>
|
||||
<td>属性</td>
|
||||
<td>解释</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>coid</td>
|
||||
<td>int(10)</td>
|
||||
<td>主键,非负,自增</td>
|
||||
<td>comment表主键</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>cid</td>
|
||||
<td>int(10)</td>
|
||||
<td>索引,非负</td>
|
||||
<td>post表主键,关联字段</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>cid</td>
|
||||
<td>int(10)</td>
|
||||
<td>索引,非负</td>
|
||||
<td>post表主键,关联字段</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>created</td>
|
||||
<td>int(10)</td>
|
||||
<td>非负,可为空</td>
|
||||
<td>评论生成时的GMT unix时间戳</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>text</td>
|
||||
<td>text</td>
|
||||
<td>可为空</td>
|
||||
<td>评论内容</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>type</td>
|
||||
<td>varchar(16)</td>
|
||||
<td>可为空</td>
|
||||
<td>评论类型</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>status</td>
|
||||
<td>varchar(16)</td>
|
||||
<td>可为空</td>
|
||||
<td>评论状态</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>author</td>
|
||||
<td>varchar(200)</td>
|
||||
<td>可为空</td>
|
||||
<td>评论用户</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## 用户表
|
||||
存储博客系统中用户的信息:
|
||||
|
||||
<table width="100%">
|
||||
<tr>
|
||||
<td>键名</td>
|
||||
<td>类型</td>
|
||||
<td>属性</td>
|
||||
<td>解释</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>uid</td>
|
||||
<td>int(10)</td>
|
||||
<td>主键,非负,自增</td>
|
||||
<td>user表主键</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>username</td>
|
||||
<td>varchar(32)</td>
|
||||
<td>唯一</td>
|
||||
<td>用户名</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>password</td>
|
||||
<td>varchar(32)</td>
|
||||
<td>可为空</td>
|
||||
<td>用户密码</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>created</td>
|
||||
<td>int(10)</td>
|
||||
<td>非负,可为空</td>
|
||||
<td>用户注册时的GMT unix时间戳</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>lastlogin</td>
|
||||
<td>int(10)</td>
|
||||
<td>非负,可为空</td>
|
||||
<td>最后登录时间</td>
|
||||
</tr>
|
||||
</table>
|
||||
## 配置表
|
||||
网站的配置信息表:
|
||||
|
||||
<table width="100%">
|
||||
<tr>
|
||||
<td>键名</td>
|
||||
<td>类型</td>
|
||||
<td>属性</td>
|
||||
<td>解释</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>name</td>
|
||||
<td>varchar(32)</td>
|
||||
<td>主键</td>
|
||||
<td>配置名称</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>uid</td>
|
||||
<td>int(10)</td>
|
||||
<td>主键,非负</td>
|
||||
<td>配置所属用户,默认为0(全局配置)</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>value</td>
|
||||
<td>text</td>
|
||||
<td>主键,非负,自增</td>
|
||||
<td>配置值</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
上面设计了一个完整的博客系统所拥有的一些功能的表,基于这些表我们可以设计出来一个强大的单用户博客,基本能够实现wordpress的一些基础单用户博客的功能。
|
||||
## links
|
||||
* [目录](<preface.md>)
|
||||
* 上一章: [项目规划](<13.1.md>)
|
||||
* 下一节: [自定义路由器设计](<13.3.md>)
|
||||
# 13.2 自定义路由器设计
|
||||
|
||||
## HTTP路由
|
||||
HTTP路由组件负责将HTTP请求交到对应的函数处理(或者是一个struct的方法),如前面小节所描述的结构图,路由在框架中相当于一个事件处理器,而这个事件包括:
|
||||
|
||||
- 用户请求的路径(例如:/user/123,/article/123),当然还有查询串信息(例如?id=11)
|
||||
- HTTP的请求method(GET、POST、PUT、DELETE、PATCH等)
|
||||
|
||||
路由器就是根据用户请求的这个信息定位到相应的处理函数。
|
||||
## 默认的路由实现
|
||||
在3.4小节有过介绍Go的http包的详解,里面介绍了Go的http包如何设计和实现路由,这里继续以一个例子来说明:
|
||||
|
||||
func fooHandler(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
|
||||
}
|
||||
|
||||
http.Handle("/foo", fooHandler)
|
||||
|
||||
http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
|
||||
})
|
||||
|
||||
log.Fatal(http.ListenAndServe(":8080", nil))
|
||||
|
||||
上面的例子调用了http默认的DefaultServeMux来添加路由,两个参数,第一个参数是前面所讲的用户请求的路径(Go中保存在r.URL.Path),第二参数是定位要执行的函数,路由的思路主要集中在两点:
|
||||
|
||||
- 添加路由信息
|
||||
- 根据用户请求转发到要执行的函数
|
||||
|
||||
Go默认的包添加是通过函数`http.Handle`和`http.HandleFunc`等来添加,底层都是调用了`DefaultServeMux.Handle(pattern string, handler Handler)`,这个函数会把路由信息存储在一个map信息中`map[string]muxEntry`,这就解决了上面说的第一点。
|
||||
|
||||
Go的监听端口,然后接收到tcp连接会扔给Handler来处理,上面的例子默认nil即为`http.DefaultServeMux`,通过`DefaultServeMux.ServeHTTP`函数来进行调度,循环上面存储的map信息,和访问url进行比对查询注册的处理函数,这样就实现了上面所说的第二点。
|
||||
|
||||
for k, v := range mux.m {
|
||||
if !pathMatch(k, path) {
|
||||
continue
|
||||
}
|
||||
if h == nil || len(k) > n {
|
||||
n = len(k)
|
||||
h = v.h
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
## beego框架路由实现
|
||||
目前几乎所有的Web应用路由实现都是基于http默认的路由器,但是默认的路由器有几个限制点:
|
||||
|
||||
- 不支持参数设定,例如/user/:uid 这种泛类型匹配
|
||||
- 无法很好的支持REST模式,无法限制访问的方法,例如上面的例子中,用户访问/foo,可以用GET、POST、DELETE、HEAD等方式访问
|
||||
- 默认的路由规则太多了,我前面自己开发了一个API的应用,路由规则有三十几条,这种路由多了之后其实可以进一步简化,通过struct的方法进行一种简化
|
||||
|
||||
beego框架的路由器基于上面的几点限制考虑设计了一种REST方式的路由实现,路由设计也是基于上面的默认设计的两点来考虑:存储路由和转发路由
|
||||
|
||||
### 存储路由
|
||||
针对前面所说的限制点,我们首先要解决参数支持就需要用到正则,第二和第三点我们通过一种变通的方法来解决,REST的方法对应到struct的方法中去,然后路由到struct而不是函数,这样在转发路由的时候就可以根据method来执行不同的方法。
|
||||
|
||||
根据上面的思路,我们设计了两个数据类型controllerInfo(保存路径和对应的struct,这里是一个reflect.Type类型)和ControllerRegistor(routers是一个slice用来保存用户添加的路由信息,已经beego框架的信息)
|
||||
|
||||
type controllerInfo struct {
|
||||
regex *regexp.Regexp
|
||||
params map[int]string
|
||||
controllerType reflect.Type
|
||||
}
|
||||
|
||||
type ControllerRegistor struct {
|
||||
routers []*controllerInfo
|
||||
Application *App
|
||||
}
|
||||
|
||||
|
||||
ControllerRegistor对外的接口函数有
|
||||
|
||||
func (p *ControllerRegistor) Add(pattern string, c ControllerInterface)
|
||||
|
||||
详细的实现如下所示:
|
||||
|
||||
func (p *ControllerRegistor) Add(pattern string, c ControllerInterface) {
|
||||
parts := strings.Split(pattern, "/")
|
||||
|
||||
j := 0
|
||||
params := make(map[int]string)
|
||||
for i, part := range parts {
|
||||
if strings.HasPrefix(part, ":") {
|
||||
expr := "([^/]+)"
|
||||
//a user may choose to override the defult expression
|
||||
// similar to expressjs: ‘/user/:id([0-9]+)’
|
||||
if index := strings.Index(part, "("); index != -1 {
|
||||
expr = part[index:]
|
||||
part = part[:index]
|
||||
}
|
||||
params[j] = part
|
||||
parts[i] = expr
|
||||
j++
|
||||
}
|
||||
}
|
||||
|
||||
//recreate the url pattern, with parameters replaced
|
||||
//by regular expressions. then compile the regex
|
||||
pattern = strings.Join(parts, "/")
|
||||
regex, regexErr := regexp.Compile(pattern)
|
||||
if regexErr != nil {
|
||||
//TODO add error handling here to avoid panic
|
||||
panic(regexErr)
|
||||
return
|
||||
}
|
||||
|
||||
//now create the Route
|
||||
t := reflect.Indirect(reflect.ValueOf(c)).Type()
|
||||
route := &controllerInfo{}
|
||||
route.regex = regex
|
||||
route.params = params
|
||||
route.controllerType = t
|
||||
|
||||
p.routers = append(p.routers, route)
|
||||
|
||||
}
|
||||
|
||||
### 静态路由实现
|
||||
上面我们实现的动态路由的实现,Go的http包默认支持静态文件处理FileServer,由于我们实现了自定义的路由器,那么静态文件也需要自己设定,beego的静态文件夹保存在全局变量StaticDir中,StaticDir是一个map类型,实现如下:
|
||||
|
||||
func (app *App) SetStaticPath(url string, path string) *App {
|
||||
StaticDir[url] = path
|
||||
return app
|
||||
}
|
||||
|
||||
应用中设置静态路径可以使用如下方式实现:
|
||||
|
||||
beego.SetStaticPath("/img","/static/img")
|
||||
|
||||
|
||||
### 转发路由
|
||||
转发路由是基于ControllerRegistor的路由信息来进行转发的,详细的实现如下代码所示:
|
||||
|
||||
// AutoRoute
|
||||
func (p *ControllerRegistor) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
if !RecoverPanic {
|
||||
// go back to panic
|
||||
panic(err)
|
||||
} else {
|
||||
Critical("Handler crashed with error", err)
|
||||
for i := 1; ; i += 1 {
|
||||
_, file, line, ok := runtime.Caller(i)
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
Critical(file, line)
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
var started bool
|
||||
for prefix, staticDir := range StaticDir {
|
||||
if strings.HasPrefix(r.URL.Path, prefix) {
|
||||
file := staticDir + r.URL.Path[len(prefix):]
|
||||
http.ServeFile(w, r, file)
|
||||
started = true
|
||||
return
|
||||
}
|
||||
}
|
||||
requestPath := r.URL.Path
|
||||
|
||||
//find a matching Route
|
||||
for _, route := range p.routers {
|
||||
|
||||
//check if Route pattern matches url
|
||||
if !route.regex.MatchString(requestPath) {
|
||||
continue
|
||||
}
|
||||
|
||||
//get submatches (params)
|
||||
matches := route.regex.FindStringSubmatch(requestPath)
|
||||
|
||||
//double check that the Route matches the URL pattern.
|
||||
if len(matches[0]) != len(requestPath) {
|
||||
continue
|
||||
}
|
||||
|
||||
params := make(map[string]string)
|
||||
if len(route.params) > 0 {
|
||||
//add url parameters to the query param map
|
||||
values := r.URL.Query()
|
||||
for i, match := range matches[1:] {
|
||||
values.Add(route.params[i], match)
|
||||
params[route.params[i]] = match
|
||||
}
|
||||
|
||||
//reassemble query params and add to RawQuery
|
||||
r.URL.RawQuery = url.Values(values).Encode() + "&" + r.URL.RawQuery
|
||||
//r.URL.RawQuery = url.Values(values).Encode()
|
||||
}
|
||||
//Invoke the request handler
|
||||
vc := reflect.New(route.controllerType)
|
||||
init := vc.MethodByName("Init")
|
||||
in := make([]reflect.Value, 2)
|
||||
ct := &Context{ResponseWriter: w, Request: r, Params: params}
|
||||
in[0] = reflect.ValueOf(ct)
|
||||
in[1] = reflect.ValueOf(route.controllerType.Name())
|
||||
init.Call(in)
|
||||
in = make([]reflect.Value, 0)
|
||||
method := vc.MethodByName("Prepare")
|
||||
method.Call(in)
|
||||
if r.Method == "GET" {
|
||||
method = vc.MethodByName("Get")
|
||||
method.Call(in)
|
||||
} else if r.Method == "POST" {
|
||||
method = vc.MethodByName("Post")
|
||||
method.Call(in)
|
||||
} else if r.Method == "HEAD" {
|
||||
method = vc.MethodByName("Head")
|
||||
method.Call(in)
|
||||
} else if r.Method == "DELETE" {
|
||||
method = vc.MethodByName("Delete")
|
||||
method.Call(in)
|
||||
} else if r.Method == "PUT" {
|
||||
method = vc.MethodByName("Put")
|
||||
method.Call(in)
|
||||
} else if r.Method == "PATCH" {
|
||||
method = vc.MethodByName("Patch")
|
||||
method.Call(in)
|
||||
} else if r.Method == "OPTIONS" {
|
||||
method = vc.MethodByName("Options")
|
||||
method.Call(in)
|
||||
}
|
||||
if AutoRender {
|
||||
method = vc.MethodByName("Render")
|
||||
method.Call(in)
|
||||
}
|
||||
method = vc.MethodByName("Finish")
|
||||
method.Call(in)
|
||||
started = true
|
||||
break
|
||||
}
|
||||
|
||||
//if no matches to url, throw a not found exception
|
||||
if started == false {
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
### 使用入门
|
||||
基于这样的路由设计之后就可以解决前面所说的三个限制点,使用的方式如下所示:
|
||||
|
||||
基本的使用注册路由:
|
||||
|
||||
beego.BeeApp.RegisterController("/", &controllers.MainController{})
|
||||
|
||||
参数注册:
|
||||
|
||||
beego.BeeApp.RegisterController("/:param", &controllers.UserController{})
|
||||
|
||||
正则匹配:
|
||||
|
||||
beego.BeeApp.RegisterController("/users/:uid([0-9]+)", &controllers.UserController{})
|
||||
|
||||
## links
|
||||
* [目录](<preface.md>)
|
||||
* 上一章: [数据库设计](<13.2.md>)
|
||||
* 下一节: [controller设计](<13.4.md>)
|
||||
376
13.3.md
376
13.3.md
@@ -1,260 +1,162 @@
|
||||
# 13.3 自定义路由器设计
|
||||
# 13.3 controller设计
|
||||
|
||||
## HTTP路由
|
||||
HTTP路由组件负责将HTTP请求交到对应的函数处理(或者是一个struct的方法),如前面小节所描述的结构图,路由在框架中相当于一个事件处理器,而这个事件包括:
|
||||
传统的MVC框架大多数是基于Action设计的后缀式映射,然而目前流行的Web趋势是REST风格的架构。尽管使用Filter或者rewrite能够通过URL重写实现REST风格的URL,但是为什么不直接设计一个全新的REST风格的 MVC框架呢?本小节就是基于这种思路来讲述如何从头设计一个基于REST风格的MVC框架中的controller,最大限度地简化Web应用的开发,您甚至编写一行代码就可以实现“Hello, world”。
|
||||
|
||||
- 用户请求的路径(例如:/user/123,/article/123),当然还有查询串信息(例如?id=11)
|
||||
- HTTP的请求method(GET、POST、PUT、DELETE、PATCH等)
|
||||
## controller作用
|
||||
MVC设计模式是目前Web应用开发中最常见的一种架构模式,通过分离 Model(模型)、View(视图)和 Controller(控制器),可以更容易实现易于扩展的UI。Model指后台返回的数据;View指需要渲染的页面,通常是模板页面,渲染后的结果通常是HTML;Controller指Web开发人员编写的处理不同URL的控制器,如前面小节讲述的路由就是转发到控制器的过程,controller在整个的MVC框架中起到了一个核心的作用,处理业务逻辑,因此控制器是整个框架中必不可少的一部分,Model和View会根据不同的业务可以不写,例如没有数据处理的逻辑处理,没有页面输出的302调整之类的就不需要Model和View,但是controller是必不可少的。
|
||||
|
||||
路由器就是根据用户请求的这个信息定位到相应的处理函数。
|
||||
## 默认的路由实现
|
||||
在3.4小节有过介绍Go的http包的详解,里面介绍了Go的http包如何设计和实现路由,这里继续以一个例子来说明:
|
||||
## beego的REST设计
|
||||
前面小节介绍了路由实现了注册struct的功能,而struct中实现了REST方式,因此我们需要设计一个用于逻辑处理controller的基类,这里主要设计了两个类型,一个struct、一个interface
|
||||
|
||||
func fooHandler(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
|
||||
}
|
||||
|
||||
http.Handle("/foo", fooHandler)
|
||||
|
||||
http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
|
||||
})
|
||||
|
||||
log.Fatal(http.ListenAndServe(":8080", nil))
|
||||
|
||||
上面的例子调用了http默认的DefaultServeMux来添加路由,两个参数,第一个参数是前面所讲的用户请求的路径(Go中保存在r.URL.Path),第二参数是定位要执行的函数,路由的思路主要集中在两点:
|
||||
|
||||
- 添加路由信息
|
||||
- 根据用户请求转发到要执行的函数
|
||||
|
||||
Go默认的包添加是通过函数`http.Handle`和`http.HandleFunc`等来添加,底层都是调用了`DefaultServeMux.Handle(pattern string, handler Handler)`,这个函数会把路由信息存储在一个map信息中`map[string]muxEntry`,这就解决了上面说的第一点。
|
||||
|
||||
Go的监听端口,然后接收到tcp连接会扔给Handler来处理,上面的例子默认nil即为`http.DefaultServeMux`,通过`DefaultServeMux.ServeHTTP`函数来进行调度,循环上面存储的map信息,和访问url进行比对查询注册的处理函数,这样就实现了上面所说的第二点。
|
||||
|
||||
for k, v := range mux.m {
|
||||
if !pathMatch(k, path) {
|
||||
continue
|
||||
}
|
||||
if h == nil || len(k) > n {
|
||||
n = len(k)
|
||||
h = v.h
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
## beego框架路由实现
|
||||
目前几乎所有的Web应用路由实现都是基于http默认的路由器,但是默认的路由器有几个限制点:
|
||||
|
||||
- 不支持参数设定,例如/user/:uid 这种泛类型匹配
|
||||
- 无法很好的支持REST模式,无法限制访问的方法,例如上面的例子中,用户访问/foo,可以用GET、POST、DELETE、HEAD等方式访问
|
||||
- 默认的路由规则太多了,我前面自己开发了一个API的应用,路由规则有三十几条,这种路由多了之后其实可以进一步简化,通过struct的方法进行一种简化
|
||||
|
||||
beego框架的路由器基于上面的几点限制考虑设计了一种REST方式的路由实现,路由设计也是基于上面的默认设计的两点来考虑:存储路由和转发路由
|
||||
|
||||
### 存储路由
|
||||
针对前面所说的限制点,我们首先要解决参数支持就需要用到正则,第二和第三点我们通过一种变通的方法来解决,REST的方法对应到struct的方法中去,然后路由到struct而不是函数,这样在转发路由的时候就可以根据method来执行不同的方法。
|
||||
|
||||
根据上面的思路,我们设计了两个数据类型controllerInfo(保存路径和对应的struct,这里是一个reflect.Type类型)和ControllerRegistor(routers是一个slice用来保存用户添加的路由信息,已经beego框架的信息)
|
||||
|
||||
type controllerInfo struct {
|
||||
regex *regexp.Regexp
|
||||
params map[int]string
|
||||
controllerType reflect.Type
|
||||
}
|
||||
|
||||
type ControllerRegistor struct {
|
||||
routers []*controllerInfo
|
||||
Application *App
|
||||
type Controller struct {
|
||||
Ct *Context
|
||||
Tpl *template.Template
|
||||
Data map[interface{}]interface{}
|
||||
ChildName string
|
||||
TplNames string
|
||||
Layout []string
|
||||
TplExt string
|
||||
}
|
||||
|
||||
|
||||
ControllerRegistor对外的接口函数有
|
||||
|
||||
func (p *ControllerRegistor) Add(pattern string, c ControllerInterface)
|
||||
|
||||
详细的实现如下所示:
|
||||
|
||||
func (p *ControllerRegistor) Add(pattern string, c ControllerInterface) {
|
||||
parts := strings.Split(pattern, "/")
|
||||
type ControllerInterface interface {
|
||||
Init(ct *Context, cn string) //初始化上下文和子类名称
|
||||
Prepare() //开始执行之前的一些处理
|
||||
Get() //method=GET的处理
|
||||
Post() //method=POST的处理
|
||||
Delete() //method=DELETE的处理
|
||||
Put() //method=PUT的处理
|
||||
Head() //method=HEAD的处理
|
||||
Patch() //method=PATCH的处理
|
||||
Options() //method=OPTIONS的处理
|
||||
Finish() //执行完成之后的处理 Render() error //执行完method对应的方法之后渲染页面
|
||||
}
|
||||
|
||||
j := 0
|
||||
params := make(map[int]string)
|
||||
for i, part := range parts {
|
||||
if strings.HasPrefix(part, ":") {
|
||||
expr := "([^/]+)"
|
||||
//a user may choose to override the defult expression
|
||||
// similar to expressjs: ‘/user/:id([0-9]+)’
|
||||
if index := strings.Index(part, "("); index != -1 {
|
||||
expr = part[index:]
|
||||
part = part[:index]
|
||||
}
|
||||
params[j] = part
|
||||
parts[i] = expr
|
||||
j++
|
||||
}
|
||||
}
|
||||
那么前面介绍的路由add的时候是定义了ControllerInterface类型,因此,只要我们实现这个接口就可以,所以我们的基类Controller实现如下的方法:
|
||||
|
||||
func (c *Controller) Init(ct *Context, cn string) {
|
||||
c.Data = make(map[interface{}]interface{})
|
||||
c.Layout = make([]string, 0)
|
||||
c.TplNames = ""
|
||||
c.ChildName = cn
|
||||
c.Ct = ct
|
||||
c.TplExt = "tpl"
|
||||
}
|
||||
|
||||
//recreate the url pattern, with parameters replaced
|
||||
//by regular expressions. then compile the regex
|
||||
pattern = strings.Join(parts, "/")
|
||||
regex, regexErr := regexp.Compile(pattern)
|
||||
if regexErr != nil {
|
||||
//TODO add error handling here to avoid panic
|
||||
panic(regexErr)
|
||||
return
|
||||
}
|
||||
|
||||
//now create the Route
|
||||
t := reflect.Indirect(reflect.ValueOf(c)).Type()
|
||||
route := &controllerInfo{}
|
||||
route.regex = regex
|
||||
route.params = params
|
||||
route.controllerType = t
|
||||
|
||||
p.routers = append(p.routers, route)
|
||||
func (c *Controller) Prepare() {
|
||||
|
||||
}
|
||||
|
||||
### 静态路由实现
|
||||
上面我们实现的动态路由的实现,Go的http包默认支持静态文件处理FileServer,由于我们实现了自定义的路由器,那么静态文件也需要自己设定,beego的静态文件夹保存在全局变量StaticDir中,StaticDir是一个map类型,实现如下:
|
||||
|
||||
func (app *App) SetStaticPath(url string, path string) *App {
|
||||
StaticDir[url] = path
|
||||
return app
|
||||
func (c *Controller) Finish() {
|
||||
|
||||
}
|
||||
|
||||
应用中设置静态路径可以使用如下方式实现:
|
||||
|
||||
beego.SetStaticPath("/img","/static/img")
|
||||
|
||||
|
||||
### 转发路由
|
||||
转发路由是基于ControllerRegistor的路由信息来进行转发的,详细的实现如下代码所示:
|
||||
|
||||
// AutoRoute
|
||||
func (p *ControllerRegistor) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
if !RecoverPanic {
|
||||
// go back to panic
|
||||
panic(err)
|
||||
} else {
|
||||
Critical("Handler crashed with error", err)
|
||||
for i := 1; ; i += 1 {
|
||||
_, file, line, ok := runtime.Caller(i)
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
Critical(file, line)
|
||||
}
|
||||
}
|
||||
func (c *Controller) Get() {
|
||||
http.Error(c.Ct.ResponseWriter, "Method Not Allowed", 405)
|
||||
}
|
||||
|
||||
func (c *Controller) Post() {
|
||||
http.Error(c.Ct.ResponseWriter, "Method Not Allowed", 405)
|
||||
}
|
||||
|
||||
func (c *Controller) Delete() {
|
||||
http.Error(c.Ct.ResponseWriter, "Method Not Allowed", 405)
|
||||
}
|
||||
|
||||
func (c *Controller) Put() {
|
||||
http.Error(c.Ct.ResponseWriter, "Method Not Allowed", 405)
|
||||
}
|
||||
|
||||
func (c *Controller) Head() {
|
||||
http.Error(c.Ct.ResponseWriter, "Method Not Allowed", 405)
|
||||
}
|
||||
|
||||
func (c *Controller) Patch() {
|
||||
http.Error(c.Ct.ResponseWriter, "Method Not Allowed", 405)
|
||||
}
|
||||
|
||||
func (c *Controller) Options() {
|
||||
http.Error(c.Ct.ResponseWriter, "Method Not Allowed", 405)
|
||||
}
|
||||
|
||||
func (c *Controller) Render() error {
|
||||
if len(c.Layout) > 0 {
|
||||
var filenames []string
|
||||
for _, file := range c.Layout {
|
||||
filenames = append(filenames, path.Join(ViewsPath, file))
|
||||
}
|
||||
}()
|
||||
var started bool
|
||||
for prefix, staticDir := range StaticDir {
|
||||
if strings.HasPrefix(r.URL.Path, prefix) {
|
||||
file := staticDir + r.URL.Path[len(prefix):]
|
||||
http.ServeFile(w, r, file)
|
||||
started = true
|
||||
return
|
||||
t, err := template.ParseFiles(filenames...)
|
||||
if err != nil {
|
||||
Trace("template ParseFiles err:", err)
|
||||
}
|
||||
err = t.ExecuteTemplate(c.Ct.ResponseWriter, c.TplNames, c.Data)
|
||||
if err != nil {
|
||||
Trace("template Execute err:", err)
|
||||
}
|
||||
} else {
|
||||
if c.TplNames == "" {
|
||||
c.TplNames = c.ChildName + "/" + c.Ct.Request.Method + "." + c.TplExt
|
||||
}
|
||||
t, err := template.ParseFiles(path.Join(ViewsPath, c.TplNames))
|
||||
if err != nil {
|
||||
Trace("template ParseFiles err:", err)
|
||||
}
|
||||
err = t.Execute(c.Ct.ResponseWriter, c.Data)
|
||||
if err != nil {
|
||||
Trace("template Execute err:", err)
|
||||
}
|
||||
}
|
||||
requestPath := r.URL.Path
|
||||
return nil
|
||||
}
|
||||
|
||||
//find a matching Route
|
||||
for _, route := range p.routers {
|
||||
|
||||
//check if Route pattern matches url
|
||||
if !route.regex.MatchString(requestPath) {
|
||||
continue
|
||||
}
|
||||
|
||||
//get submatches (params)
|
||||
matches := route.regex.FindStringSubmatch(requestPath)
|
||||
|
||||
//double check that the Route matches the URL pattern.
|
||||
if len(matches[0]) != len(requestPath) {
|
||||
continue
|
||||
}
|
||||
|
||||
params := make(map[string]string)
|
||||
if len(route.params) > 0 {
|
||||
//add url parameters to the query param map
|
||||
values := r.URL.Query()
|
||||
for i, match := range matches[1:] {
|
||||
values.Add(route.params[i], match)
|
||||
params[route.params[i]] = match
|
||||
}
|
||||
|
||||
//reassemble query params and add to RawQuery
|
||||
r.URL.RawQuery = url.Values(values).Encode() + "&" + r.URL.RawQuery
|
||||
//r.URL.RawQuery = url.Values(values).Encode()
|
||||
}
|
||||
//Invoke the request handler
|
||||
vc := reflect.New(route.controllerType)
|
||||
init := vc.MethodByName("Init")
|
||||
in := make([]reflect.Value, 2)
|
||||
ct := &Context{ResponseWriter: w, Request: r, Params: params}
|
||||
in[0] = reflect.ValueOf(ct)
|
||||
in[1] = reflect.ValueOf(route.controllerType.Name())
|
||||
init.Call(in)
|
||||
in = make([]reflect.Value, 0)
|
||||
method := vc.MethodByName("Prepare")
|
||||
method.Call(in)
|
||||
if r.Method == "GET" {
|
||||
method = vc.MethodByName("Get")
|
||||
method.Call(in)
|
||||
} else if r.Method == "POST" {
|
||||
method = vc.MethodByName("Post")
|
||||
method.Call(in)
|
||||
} else if r.Method == "HEAD" {
|
||||
method = vc.MethodByName("Head")
|
||||
method.Call(in)
|
||||
} else if r.Method == "DELETE" {
|
||||
method = vc.MethodByName("Delete")
|
||||
method.Call(in)
|
||||
} else if r.Method == "PUT" {
|
||||
method = vc.MethodByName("Put")
|
||||
method.Call(in)
|
||||
} else if r.Method == "PATCH" {
|
||||
method = vc.MethodByName("Patch")
|
||||
method.Call(in)
|
||||
} else if r.Method == "OPTIONS" {
|
||||
method = vc.MethodByName("Options")
|
||||
method.Call(in)
|
||||
}
|
||||
if AutoRender {
|
||||
method = vc.MethodByName("Render")
|
||||
method.Call(in)
|
||||
}
|
||||
method = vc.MethodByName("Finish")
|
||||
method.Call(in)
|
||||
started = true
|
||||
break
|
||||
}
|
||||
|
||||
//if no matches to url, throw a not found exception
|
||||
if started == false {
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}
|
||||
func (c *Controller) Redirect(url string, code int) {
|
||||
c.Ct.Redirect(code, url)
|
||||
}
|
||||
|
||||
### 使用入门
|
||||
基于这样的路由设计之后就可以解决前面所说的三个限制点,使用的方式如下所示:
|
||||
上面的controller基类完成了接口定义的函数,通过路由根据url执行相应的controller的原则,会依次执行如下的函数:
|
||||
|
||||
基本的使用注册路由:
|
||||
Init() 初始化
|
||||
Prepare() 执行之前的初始化,每个继承的子类可以来实现该函数
|
||||
method() 根据不同的method执行不同的函数:GET、POST、PUT、HEAD等,子类来实现这些函数,如果没实现,那么默认都是403
|
||||
Render() 可选,根据全局变量AutoRender来判断是否执行
|
||||
Finish() 执行完之后执行的操作,每个继承的子类可以来实现该函数
|
||||
|
||||
beego.BeeApp.RegisterController("/", &controllers.MainController{})
|
||||
## 应用指南
|
||||
上面beego框架中完成了controller基类的设计,那么我们在我们的应用中可以这样来设计我们的方法:
|
||||
|
||||
package controllers
|
||||
|
||||
参数注册:
|
||||
|
||||
beego.BeeApp.RegisterController("/:param", &controllers.UserController{})
|
||||
import (
|
||||
"github.com/astaxie/beego"
|
||||
)
|
||||
|
||||
正则匹配:
|
||||
type MainController struct {
|
||||
beego.Controller
|
||||
}
|
||||
|
||||
func (this *MainController) Get() {
|
||||
this.Data["Username"] = "astaxie"
|
||||
this.Data["Email"] = "astaxie@gmail.com"
|
||||
this.TplNames = "index.tpl"
|
||||
}
|
||||
|
||||
上面的方式我们实现了子类MainController,实现了Get方法,那么如果用户通过其他的方式(POST/HEAD等)来访问该资源都将返回403,而如果是Get来访问,因为我们设置了AutoRender=true,那么在执行玩Get方法之后会自动执行Render函数,就会显示如下界面:
|
||||
|
||||
beego.BeeApp.RegisterController("/users/:uid([0-9]+)", &controllers.UserController{})
|
||||
|
||||
## links
|
||||
* [目录](<preface.md>)
|
||||
* 上一章: [数据库设计](<13.2.md>)
|
||||
* 下一节: [controller设计](<13.4.md>)
|
||||

|
||||
|
||||
index.tpl的代码如下所示,我们可以看到数据的设置和显示都是相当的简单方便:
|
||||
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>beego welcome template</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Hello, world!{{.Username}},{{.Email}}</h1>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
## links
|
||||
* [目录](<preface.md>)
|
||||
* 上一章: [自定义路由器设计](<13.2.md>)
|
||||
* 下一节: [日志和配置设计](<13.4.md>)
|
||||
380
13.4.md
380
13.4.md
@@ -1,162 +1,248 @@
|
||||
# 13.4 controller设计
|
||||
# 13.4 日志和配置设计
|
||||
|
||||
传统的MVC框架大多数是基于Action设计的后缀式映射,然而目前流行的Web趋势是REST风格的架构。尽管使用Filter或者rewrite能够通过URL重写实现REST风格的URL,但是为什么不直接设计一个全新的REST风格的 MVC框架呢?本小节就是基于这种思路来讲述如何从头设计一个基于REST风格的MVC框架中的controller,最大限度地简化Web应用的开发,您甚至编写一行代码就可以实现“Hello, world”。
|
||||
## 日志和配置的重要性
|
||||
前面已经介绍过日志在我们程序开发中起着很重要的作用,通过日志我们可以记录调试我们的信息,当初介绍过一个日志系统seelog,根据不同的level输出不同的日志,这个对于程序开发和程序部署来说至关重要。我们可以在程序开发中设置level低一点,部署的时候把level设置高,这样我们开发中的调试信息可以屏蔽掉。
|
||||
|
||||
## controller作用
|
||||
MVC设计模式是目前Web应用开发中最常见的一种架构模式,通过分离 Model(模型)、View(视图)和 Controller(控制器),可以更容易实现易于扩展的UI。Model指后台返回的数据;View指需要渲染的页面,通常是模板页面,渲染后的结果通常是HTML;Controller指Web开发人员编写的处理不同URL的控制器,如前面小节讲述的路由就是转发到控制器的过程,controller在整个的MVC框架中起到了一个核心的作用,处理业务逻辑,因此控制器是整个框架中必不可少的一部分,Model和View会根据不同的业务可以不写,例如没有数据处理的逻辑处理,没有页面输出的302调整之类的就不需要Model和View,但是controller是必不可少的。
|
||||
配置模块对于应用部署牵涉到服务器不同的一些配置信息非常有用,例如一些数据库配置信息、监听端口、监听地址等都是可以通过配置文件来配置,这样我们的应用程序就具有很强的灵活性,可以通过配置文件的配置部署在不同的机器上,可以连接不同的数据库之类的。
|
||||
|
||||
## beego的REST设计
|
||||
前面小节介绍了路由实现了注册struct的功能,而struct中实现了REST方式,因此我们需要设计一个用于逻辑处理controller的基类,这里主要设计了两个类型,一个struct、一个interface
|
||||
## beego的日志设计
|
||||
beego的日志设计部署思路来自于seelog,根据不同的level来记录日志,但是beego设计的日志系统比较轻量级,采用了系统的log.Logger接口,默认输出到os.Stdout,用户可以实现这个接口然后通过beego.SetLogger设置自定义的输出,详细的实现如下所示:
|
||||
|
||||
type Controller struct {
|
||||
Ct *Context
|
||||
Tpl *template.Template
|
||||
Data map[interface{}]interface{}
|
||||
ChildName string
|
||||
TplNames string
|
||||
Layout []string
|
||||
TplExt string
|
||||
}
|
||||
|
||||
type ControllerInterface interface {
|
||||
Init(ct *Context, cn string) //初始化上下文和子类名称
|
||||
Prepare() //开始执行之前的一些处理
|
||||
Get() //method=GET的处理
|
||||
Post() //method=POST的处理
|
||||
Delete() //method=DELETE的处理
|
||||
Put() //method=PUT的处理
|
||||
Head() //method=HEAD的处理
|
||||
Patch() //method=PATCH的处理
|
||||
Options() //method=OPTIONS的处理
|
||||
Finish() //执行完成之后的处理 Render() error //执行完method对应的方法之后渲染页面
|
||||
}
|
||||
|
||||
那么前面介绍的路由add的时候是定义了ControllerInterface类型,因此,只要我们实现这个接口就可以,所以我们的基类Controller实现如下的方法:
|
||||
|
||||
func (c *Controller) Init(ct *Context, cn string) {
|
||||
c.Data = make(map[interface{}]interface{})
|
||||
c.Layout = make([]string, 0)
|
||||
c.TplNames = ""
|
||||
c.ChildName = cn
|
||||
c.Ct = ct
|
||||
c.TplExt = "tpl"
|
||||
}
|
||||
|
||||
func (c *Controller) Prepare() {
|
||||
|
||||
}
|
||||
|
||||
func (c *Controller) Finish() {
|
||||
|
||||
}
|
||||
|
||||
func (c *Controller) Get() {
|
||||
http.Error(c.Ct.ResponseWriter, "Method Not Allowed", 405)
|
||||
}
|
||||
|
||||
func (c *Controller) Post() {
|
||||
http.Error(c.Ct.ResponseWriter, "Method Not Allowed", 405)
|
||||
}
|
||||
|
||||
func (c *Controller) Delete() {
|
||||
http.Error(c.Ct.ResponseWriter, "Method Not Allowed", 405)
|
||||
}
|
||||
|
||||
func (c *Controller) Put() {
|
||||
http.Error(c.Ct.ResponseWriter, "Method Not Allowed", 405)
|
||||
}
|
||||
|
||||
func (c *Controller) Head() {
|
||||
http.Error(c.Ct.ResponseWriter, "Method Not Allowed", 405)
|
||||
}
|
||||
|
||||
func (c *Controller) Patch() {
|
||||
http.Error(c.Ct.ResponseWriter, "Method Not Allowed", 405)
|
||||
}
|
||||
|
||||
func (c *Controller) Options() {
|
||||
http.Error(c.Ct.ResponseWriter, "Method Not Allowed", 405)
|
||||
}
|
||||
|
||||
func (c *Controller) Render() error {
|
||||
if len(c.Layout) > 0 {
|
||||
var filenames []string
|
||||
for _, file := range c.Layout {
|
||||
filenames = append(filenames, path.Join(ViewsPath, file))
|
||||
}
|
||||
t, err := template.ParseFiles(filenames...)
|
||||
if err != nil {
|
||||
Trace("template ParseFiles err:", err)
|
||||
}
|
||||
err = t.ExecuteTemplate(c.Ct.ResponseWriter, c.TplNames, c.Data)
|
||||
if err != nil {
|
||||
Trace("template Execute err:", err)
|
||||
}
|
||||
} else {
|
||||
if c.TplNames == "" {
|
||||
c.TplNames = c.ChildName + "/" + c.Ct.Request.Method + "." + c.TplExt
|
||||
}
|
||||
t, err := template.ParseFiles(path.Join(ViewsPath, c.TplNames))
|
||||
if err != nil {
|
||||
Trace("template ParseFiles err:", err)
|
||||
}
|
||||
err = t.Execute(c.Ct.ResponseWriter, c.Data)
|
||||
if err != nil {
|
||||
Trace("template Execute err:", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Controller) Redirect(url string, code int) {
|
||||
c.Ct.Redirect(code, url)
|
||||
}
|
||||
|
||||
上面的controller基类完成了接口定义的函数,通过路由根据url执行相应的controller的原则,会依次执行如下的函数:
|
||||
|
||||
Init() 初始化
|
||||
Prepare() 执行之前的初始化,每个继承的子类可以来实现该函数
|
||||
method() 根据不同的method执行不同的函数:GET、POST、PUT、HEAD等,子类来实现这些函数,如果没实现,那么默认都是403
|
||||
Render() 可选,根据全局变量AutoRender来判断是否执行
|
||||
Finish() 执行完之后执行的操作,每个继承的子类可以来实现该函数
|
||||
|
||||
## 应用指南
|
||||
上面beego框架中完成了controller基类的设计,那么我们在我们的应用中可以这样来设计我们的方法:
|
||||
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"github.com/astaxie/beego"
|
||||
// Log levels to control the logging output.
|
||||
const (
|
||||
LevelTrace = iota
|
||||
LevelDebug
|
||||
LevelInfo
|
||||
LevelWarning
|
||||
LevelError
|
||||
LevelCritical
|
||||
)
|
||||
|
||||
type MainController struct {
|
||||
beego.Controller
|
||||
// logLevel controls the global log level used by the logger.
|
||||
var level = LevelTrace
|
||||
|
||||
// LogLevel returns the global log level and can be used in
|
||||
// own implementations of the logger interface.
|
||||
func Level() int {
|
||||
return level
|
||||
}
|
||||
|
||||
func (this *MainController) Get() {
|
||||
this.Data["Username"] = "astaxie"
|
||||
this.Data["Email"] = "astaxie@gmail.com"
|
||||
this.TplNames = "index.tpl"
|
||||
// SetLogLevel sets the global log level used by the simple
|
||||
// logger.
|
||||
func SetLevel(l int) {
|
||||
level = l
|
||||
}
|
||||
|
||||
上面的方式我们实现了子类MainController,实现了Get方法,那么如果用户通过其他的方式(POST/HEAD等)来访问该资源都将返回403,而如果是Get来访问,因为我们设置了AutoRender=true,那么在执行玩Get方法之后会自动执行Render函数,就会显示如下界面:
|
||||
上面这一段实现了日志系统的日志分级,默认的级别是Trace,用户通过SetLevel可以设置不同的分级。
|
||||
|
||||
// logger references the used application logger.
|
||||
var BeeLogger = log.New(os.Stdout, "", log.Ldate|log.Ltime)
|
||||
|
||||
// SetLogger sets a new logger.
|
||||
func SetLogger(l *log.Logger) {
|
||||
BeeLogger = l
|
||||
}
|
||||
|
||||
// Trace logs a message at trace level.
|
||||
func Trace(v ...interface{}) {
|
||||
if level <= LevelTrace {
|
||||
BeeLogger.Printf("[T] %v\n", v)
|
||||
}
|
||||
}
|
||||
|
||||
// Debug logs a message at debug level.
|
||||
func Debug(v ...interface{}) {
|
||||
if level <= LevelDebug {
|
||||
BeeLogger.Printf("[D] %v\n", v)
|
||||
}
|
||||
}
|
||||
|
||||
// Info logs a message at info level.
|
||||
func Info(v ...interface{}) {
|
||||
if level <= LevelInfo {
|
||||
BeeLogger.Printf("[I] %v\n", v)
|
||||
}
|
||||
}
|
||||
|
||||
// Warning logs a message at warning level.
|
||||
func Warn(v ...interface{}) {
|
||||
if level <= LevelWarning {
|
||||
BeeLogger.Printf("[W] %v\n", v)
|
||||
}
|
||||
}
|
||||
|
||||
// Error logs a message at error level.
|
||||
func Error(v ...interface{}) {
|
||||
if level <= LevelError {
|
||||
BeeLogger.Printf("[E] %v\n", v)
|
||||
}
|
||||
}
|
||||
|
||||
// Critical logs a message at critical level.
|
||||
func Critical(v ...interface{}) {
|
||||
if level <= LevelCritical {
|
||||
BeeLogger.Printf("[C] %v\n", v)
|
||||
}
|
||||
}
|
||||
|
||||

|
||||
上面这一段代码默认初始化了一个BeeLogger对象,默认输出到os.Stdout,用户可以通过beego.SetLogger来设置实现了logger的接口输出。这里面实现了六个函数:
|
||||
|
||||
index.tpl的代码如下所示,我们可以看到数据的设置和显示都是相当的简单方便:
|
||||
- Trace(一般的记录信息,举例如下:)
|
||||
- "Entered parse function validation block"
|
||||
- "Validation: entered second 'if'"
|
||||
- "Dictionary 'Dict' is empty. Using default value"
|
||||
- Debug(调试信息,举例如下:)
|
||||
- "Web page requested: http://somesite.com Params='...'"
|
||||
- "Response generated. Response size: 10000. Sending."
|
||||
- "New file received. Type:PNG Size:20000"
|
||||
- Info(打印信息,举例如下:)
|
||||
- "Web server restarted"
|
||||
- "Hourly statistics: Requested pages: 12345 Errors: 123 ..."
|
||||
- "Service paused. Waiting for 'resume' call"
|
||||
- Warn(警告信息,举例如下:)
|
||||
- "Cache corrupted for file='test.file'. Reading from back-end"
|
||||
- "Database 192.168.0.7/DB not responding. Using backup 192.168.0.8/DB"
|
||||
- "No response from statistics server. Statistics not sent"
|
||||
- Error(错误信息,举例如下:)
|
||||
- "Internal error. Cannot process request #12345 Error:...."
|
||||
- "Cannot perform login: credentials DB not responding"
|
||||
- Critical(致命错误,举例如下:)
|
||||
- "Critical panic received: .... Shutting down"
|
||||
- "Fatal error: ... App is shutting down to prevent data corruption or loss"
|
||||
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>beego welcome template</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Hello, world!{{.Username}},{{.Email}}</h1>
|
||||
</body>
|
||||
</html>
|
||||
可以看到每个函数里面都有对level的判断,所以如果我们在部署的时候设置了level=LevelWarning,那么Trace、Debug、Info这三个函数都不会有任何的输出,以此类推。
|
||||
|
||||
|
||||
## links
|
||||
* [目录](<preface.md>)
|
||||
* 上一章: [自定义路由器设计](<13.3.md>)
|
||||
* 下一节: [日志和配置设计](<13.5.md>)
|
||||
## beego的配置设计
|
||||
配置信息的解析,beego实现了一个key=value的配置文件读取,类似ini配置文件的格式,就是一个文件解析的过程,然后把解析的数据保存到map中,最后在调用的时候通过几个string、int之类的函数调用返回相应的值,具体的实现请看下面:
|
||||
|
||||
首先定义了一些ini配置文件的一些全局性常量 :
|
||||
|
||||
var (
|
||||
bComment = []byte{'#'}
|
||||
bEmpty = []byte{}
|
||||
bEqual = []byte{'='}
|
||||
bDQuote = []byte{'"'}
|
||||
)
|
||||
|
||||
定义了配置文件的格式:
|
||||
|
||||
// A Config represents the configuration.
|
||||
type Config struct {
|
||||
filename string
|
||||
comment map[int][]string // id: []{comment, key...}; id 1 is for main comment.
|
||||
data map[string]string // key: value
|
||||
offset map[string]int64 // key: offset; for editing.
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
定义了解析文件的函数,解析文件的过程是打开文件,然后一行一行的读取,解析注释、空行和key=value数据:
|
||||
|
||||
// ParseFile creates a new Config and parses the file configuration from the
|
||||
// named file.
|
||||
func LoadConfig(name string) (*Config, error) {
|
||||
file, err := os.Open(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cfg := &Config{
|
||||
file.Name(),
|
||||
make(map[int][]string),
|
||||
make(map[string]string),
|
||||
make(map[string]int64),
|
||||
sync.RWMutex{},
|
||||
}
|
||||
cfg.Lock()
|
||||
defer cfg.Unlock()
|
||||
defer file.Close()
|
||||
|
||||
var comment bytes.Buffer
|
||||
buf := bufio.NewReader(file)
|
||||
|
||||
for nComment, off := 0, int64(1); ; {
|
||||
line, _, err := buf.ReadLine()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if bytes.Equal(line, bEmpty) {
|
||||
continue
|
||||
}
|
||||
|
||||
off += int64(len(line))
|
||||
|
||||
if bytes.HasPrefix(line, bComment) {
|
||||
line = bytes.TrimLeft(line, "#")
|
||||
line = bytes.TrimLeftFunc(line, unicode.IsSpace)
|
||||
comment.Write(line)
|
||||
comment.WriteByte('\n')
|
||||
continue
|
||||
}
|
||||
if comment.Len() != 0 {
|
||||
cfg.comment[nComment] = []string{comment.String()}
|
||||
comment.Reset()
|
||||
nComment++
|
||||
}
|
||||
|
||||
val := bytes.SplitN(line, bEqual, 2)
|
||||
if bytes.HasPrefix(val[1], bDQuote) {
|
||||
val[1] = bytes.Trim(val[1], `"`)
|
||||
}
|
||||
|
||||
key := strings.TrimSpace(string(val[0]))
|
||||
cfg.comment[nComment-1] = append(cfg.comment[nComment-1], key)
|
||||
cfg.data[key] = strings.TrimSpace(string(val[1]))
|
||||
cfg.offset[key] = off
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
下面实现了一些读取配置文件的函数,返回的值确定为bool、int、float64或string:
|
||||
|
||||
// Bool returns the boolean value for a given key.
|
||||
func (c *Config) Bool(key string) (bool, error) {
|
||||
return strconv.ParseBool(c.data[key])
|
||||
}
|
||||
|
||||
// Int returns the integer value for a given key.
|
||||
func (c *Config) Int(key string) (int, error) {
|
||||
return strconv.Atoi(c.data[key])
|
||||
}
|
||||
|
||||
// Float returns the float value for a given key.
|
||||
func (c *Config) Float(key string) (float64, error) {
|
||||
return strconv.ParseFloat(c.data[key], 64)
|
||||
}
|
||||
|
||||
// String returns the string value for a given key.
|
||||
func (c *Config) String(key string) string {
|
||||
return c.data[key]
|
||||
}
|
||||
|
||||
## 应用指南
|
||||
下面这个函数是我一个应用中的例子,用来获取远程url地址的json数据,实现如下:
|
||||
|
||||
func GetJson() {
|
||||
resp, err := http.Get(beego.AppConfig.String("url"))
|
||||
if err != nil {
|
||||
beego.Critical("http get info error")
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
err = json.Unmarshal(body, &AllInfo)
|
||||
if err != nil {
|
||||
beego.Critical("error:", err)
|
||||
}
|
||||
}
|
||||
|
||||
函数中调用了框架的日志函数`beego.Critical`函数用来报错,调用了`beego.AppConfig.String("url")`用来获取配置文件中的信息,配置文件的信息如下(app.conf):
|
||||
|
||||
appname = hs
|
||||
url ="http://www.api.com/api.html"
|
||||
|
||||
|
||||
## links
|
||||
* [目录](<preface.md>)
|
||||
* 上一章: [controller设计](<13.3.md>)
|
||||
* 下一节: [实现博客的增删改](<13.5.md>)
|
||||
499
13.5.md
499
13.5.md
@@ -1,248 +1,259 @@
|
||||
# 13.5 日志和配置设计
|
||||
|
||||
## 日志和配置的重要性
|
||||
前面已经介绍过日志在我们程序开发中起着很重要的作用,通过日志我们可以记录调试我们的信息,当初介绍过一个日志系统seelog,根据不同的level输出不同的日志,这个对于程序开发和程序部署来说至关重要。我们可以在程序开发中设置level低一点,部署的时候把level设置高,这样我们开发中的调试信息可以屏蔽掉。
|
||||
|
||||
配置模块对于应用部署牵涉到服务器不同的一些配置信息非常有用,例如一些数据库配置信息、监听端口、监听地址等都是可以通过配置文件来配置,这样我们的应用程序就具有很强的灵活性,可以通过配置文件的配置部署在不同的机器上,可以连接不同的数据库之类的。
|
||||
|
||||
## beego的日志设计
|
||||
beego的日志设计部署思路来自于seelog,根据不同的level来记录日志,但是beego设计的日志系统比较轻量级,采用了系统的log.Logger接口,默认输出到os.Stdout,用户可以实现这个接口然后通过beego.SetLogger设置自定义的输出,详细的实现如下所示:
|
||||
|
||||
|
||||
// Log levels to control the logging output.
|
||||
const (
|
||||
LevelTrace = iota
|
||||
LevelDebug
|
||||
LevelInfo
|
||||
LevelWarning
|
||||
LevelError
|
||||
LevelCritical
|
||||
)
|
||||
|
||||
// logLevel controls the global log level used by the logger.
|
||||
var level = LevelTrace
|
||||
|
||||
// LogLevel returns the global log level and can be used in
|
||||
// own implementations of the logger interface.
|
||||
func Level() int {
|
||||
return level
|
||||
}
|
||||
|
||||
// SetLogLevel sets the global log level used by the simple
|
||||
// logger.
|
||||
func SetLevel(l int) {
|
||||
level = l
|
||||
}
|
||||
|
||||
上面这一段实现了日志系统的日志分级,默认的级别是Trace,用户通过SetLevel可以设置不同的分级。
|
||||
|
||||
// logger references the used application logger.
|
||||
var BeeLogger = log.New(os.Stdout, "", log.Ldate|log.Ltime)
|
||||
|
||||
// SetLogger sets a new logger.
|
||||
func SetLogger(l *log.Logger) {
|
||||
BeeLogger = l
|
||||
}
|
||||
|
||||
// Trace logs a message at trace level.
|
||||
func Trace(v ...interface{}) {
|
||||
if level <= LevelTrace {
|
||||
BeeLogger.Printf("[T] %v\n", v)
|
||||
}
|
||||
}
|
||||
|
||||
// Debug logs a message at debug level.
|
||||
func Debug(v ...interface{}) {
|
||||
if level <= LevelDebug {
|
||||
BeeLogger.Printf("[D] %v\n", v)
|
||||
}
|
||||
}
|
||||
|
||||
// Info logs a message at info level.
|
||||
func Info(v ...interface{}) {
|
||||
if level <= LevelInfo {
|
||||
BeeLogger.Printf("[I] %v\n", v)
|
||||
}
|
||||
}
|
||||
|
||||
// Warning logs a message at warning level.
|
||||
func Warn(v ...interface{}) {
|
||||
if level <= LevelWarning {
|
||||
BeeLogger.Printf("[W] %v\n", v)
|
||||
}
|
||||
}
|
||||
|
||||
// Error logs a message at error level.
|
||||
func Error(v ...interface{}) {
|
||||
if level <= LevelError {
|
||||
BeeLogger.Printf("[E] %v\n", v)
|
||||
}
|
||||
}
|
||||
|
||||
// Critical logs a message at critical level.
|
||||
func Critical(v ...interface{}) {
|
||||
if level <= LevelCritical {
|
||||
BeeLogger.Printf("[C] %v\n", v)
|
||||
}
|
||||
}
|
||||
|
||||
上面这一段代码默认初始化了一个BeeLogger对象,默认输出到os.Stdout,用户可以通过beego.SetLogger来设置实现了logger的接口输出。这里面实现了六个函数:
|
||||
|
||||
- Trace(一般的记录信息,举例如下:)
|
||||
- "Entered parse function validation block"
|
||||
- "Validation: entered second 'if'"
|
||||
- "Dictionary 'Dict' is empty. Using default value"
|
||||
- Debug(调试信息,举例如下:)
|
||||
- "Web page requested: http://somesite.com Params='...'"
|
||||
- "Response generated. Response size: 10000. Sending."
|
||||
- "New file received. Type:PNG Size:20000"
|
||||
- Info(打印信息,举例如下:)
|
||||
- "Web server restarted"
|
||||
- "Hourly statistics: Requested pages: 12345 Errors: 123 ..."
|
||||
- "Service paused. Waiting for 'resume' call"
|
||||
- Warn(警告信息,举例如下:)
|
||||
- "Cache corrupted for file='test.file'. Reading from back-end"
|
||||
- "Database 192.168.0.7/DB not responding. Using backup 192.168.0.8/DB"
|
||||
- "No response from statistics server. Statistics not sent"
|
||||
- Error(错误信息,举例如下:)
|
||||
- "Internal error. Cannot process request #12345 Error:...."
|
||||
- "Cannot perform login: credentials DB not responding"
|
||||
- Critical(致命错误,举例如下:)
|
||||
- "Critical panic received: .... Shutting down"
|
||||
- "Fatal error: ... App is shutting down to prevent data corruption or loss"
|
||||
|
||||
可以看到每个函数里面都有对level的判断,所以如果我们在部署的时候设置了level=LevelWarning,那么Trace、Debug、Info这三个函数都不会有任何的输出,以此类推。
|
||||
|
||||
## beego的配置设计
|
||||
配置信息的解析,beego实现了一个key=value的配置文件读取,类似ini配置文件的格式,就是一个文件解析的过程,然后把解析的数据保存到map中,最后在调用的时候通过几个string、int之类的函数调用返回相应的值,具体的实现请看下面:
|
||||
|
||||
首先定义了一些ini配置文件的一些全局性常量 :
|
||||
|
||||
var (
|
||||
bComment = []byte{'#'}
|
||||
bEmpty = []byte{}
|
||||
bEqual = []byte{'='}
|
||||
bDQuote = []byte{'"'}
|
||||
)
|
||||
|
||||
定义了配置文件的格式:
|
||||
|
||||
// A Config represents the configuration.
|
||||
type Config struct {
|
||||
filename string
|
||||
comment map[int][]string // id: []{comment, key...}; id 1 is for main comment.
|
||||
data map[string]string // key: value
|
||||
offset map[string]int64 // key: offset; for editing.
|
||||
sync.RWMutex
|
||||
}
|
||||
|
||||
定义了解析文件的函数,解析文件的过程是打开文件,然后一行一行的读取,解析注释、空行和key=value数据:
|
||||
|
||||
// ParseFile creates a new Config and parses the file configuration from the
|
||||
// named file.
|
||||
func LoadConfig(name string) (*Config, error) {
|
||||
file, err := os.Open(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cfg := &Config{
|
||||
file.Name(),
|
||||
make(map[int][]string),
|
||||
make(map[string]string),
|
||||
make(map[string]int64),
|
||||
sync.RWMutex{},
|
||||
}
|
||||
cfg.Lock()
|
||||
defer cfg.Unlock()
|
||||
defer file.Close()
|
||||
|
||||
var comment bytes.Buffer
|
||||
buf := bufio.NewReader(file)
|
||||
|
||||
for nComment, off := 0, int64(1); ; {
|
||||
line, _, err := buf.ReadLine()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if bytes.Equal(line, bEmpty) {
|
||||
continue
|
||||
}
|
||||
|
||||
off += int64(len(line))
|
||||
|
||||
if bytes.HasPrefix(line, bComment) {
|
||||
line = bytes.TrimLeft(line, "#")
|
||||
line = bytes.TrimLeftFunc(line, unicode.IsSpace)
|
||||
comment.Write(line)
|
||||
comment.WriteByte('\n')
|
||||
continue
|
||||
}
|
||||
if comment.Len() != 0 {
|
||||
cfg.comment[nComment] = []string{comment.String()}
|
||||
comment.Reset()
|
||||
nComment++
|
||||
}
|
||||
|
||||
val := bytes.SplitN(line, bEqual, 2)
|
||||
if bytes.HasPrefix(val[1], bDQuote) {
|
||||
val[1] = bytes.Trim(val[1], `"`)
|
||||
}
|
||||
|
||||
key := strings.TrimSpace(string(val[0]))
|
||||
cfg.comment[nComment-1] = append(cfg.comment[nComment-1], key)
|
||||
cfg.data[key] = strings.TrimSpace(string(val[1]))
|
||||
cfg.offset[key] = off
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
下面实现了一些读取配置文件的函数,返回的值确定为bool、int、float64或string:
|
||||
|
||||
// Bool returns the boolean value for a given key.
|
||||
func (c *Config) Bool(key string) (bool, error) {
|
||||
return strconv.ParseBool(c.data[key])
|
||||
}
|
||||
|
||||
// Int returns the integer value for a given key.
|
||||
func (c *Config) Int(key string) (int, error) {
|
||||
return strconv.Atoi(c.data[key])
|
||||
}
|
||||
|
||||
// Float returns the float value for a given key.
|
||||
func (c *Config) Float(key string) (float64, error) {
|
||||
return strconv.ParseFloat(c.data[key], 64)
|
||||
}
|
||||
|
||||
// String returns the string value for a given key.
|
||||
func (c *Config) String(key string) string {
|
||||
return c.data[key]
|
||||
}
|
||||
|
||||
## 应用指南
|
||||
下面这个函数是我一个应用中的例子,用来获取远程url地址的json数据,实现如下:
|
||||
|
||||
func GetJson() {
|
||||
resp, err := http.Get(beego.AppConfig.String("url"))
|
||||
if err != nil {
|
||||
beego.Critical("http get info error")
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
err = json.Unmarshal(body, &AllInfo)
|
||||
if err != nil {
|
||||
beego.Critical("error:", err)
|
||||
}
|
||||
}
|
||||
|
||||
函数中调用了框架的日志函数`beego.Critical`函数用来报错,调用了`beego.AppConfig.String("url")`用来获取配置文件中的信息,配置文件的信息如下(app.conf):
|
||||
|
||||
appname = hs
|
||||
url ="http://www.api.com/api.html"
|
||||
# 13.5 实现博客的增删改
|
||||
|
||||
前面介绍了beego框架实现的整体构思以及部分实现的伪代码,这小节介绍通过beego建立一个博客系统,包括博客浏览、添加、修改、删除等操作。
|
||||
## 博客目录
|
||||
博客目录如下所示:
|
||||
|
||||
/main.go
|
||||
/views:
|
||||
/view.tpl
|
||||
/new.tpl
|
||||
/layout.tpl
|
||||
/index.tpl
|
||||
/edit.tpl
|
||||
/models/model.go
|
||||
/controllers:
|
||||
/index.go
|
||||
/view.go
|
||||
/new.go
|
||||
/delete.go
|
||||
/edit.go
|
||||
|
||||
|
||||
## 博客路由
|
||||
博客主要的路由规则如下所示:
|
||||
|
||||
//显示博客首页
|
||||
beego.RegisterController("/", &controllers.IndexController{})
|
||||
//查看博客详细信息
|
||||
beego.RegisterController("/view/:id([0-9]+)", &controllers.ViewController{})
|
||||
//新建博客博文
|
||||
beego.RegisterController("/new", &controllers.NewController{})
|
||||
//删除博文
|
||||
beego.RegisterController("/delete/:id([0-9]+)", &controllers.DeleteController{})
|
||||
//编辑博文
|
||||
beego.RegisterController("/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() {
|
||||
inputs := this.Input()
|
||||
id, _ := strconv.Atoi(this.Ctx.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() {
|
||||
inputs := this.Input()
|
||||
id, _ := strconv.Atoi(this.Ctx.Params[":id"])
|
||||
this.Data["Post"] = models.GetBlog(id)
|
||||
this.Layout = "layout.tpl"
|
||||
this.TplNames = "new.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() {
|
||||
inputs := this.Input()
|
||||
id, _ := strconv.Atoi(this.Ctx.Params[":id"])
|
||||
this.Data["Post"] = models.DelBlog(id)
|
||||
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(&blogs)
|
||||
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>)
|
||||
* 上一章: [controller设计](<13.4.md>)
|
||||
* 下一节: [实现博客的增删改](<13.6.md>)
|
||||
* 上一章: [数据库操作](<13.4.md>)
|
||||
* 下一节: [小结](<13.6.md>)
|
||||
7
13.6.md
7
13.6.md
@@ -1,6 +1,7 @@
|
||||
# 13.6 实现博客的增删改
|
||||
# 13.6 小结
|
||||
这一章我们主要介绍了如何实现一个基础的Go语言框架,框架包含有路由设计,由于Go内置的http包中路由的一些不足点,我们设计了动态路由规则,然后介绍了MVC模式中的Controller设计,controller实现了REST的实现,这个主要思路来源于tornado框架,然后设计实现了模板的layout以及自动化渲染等技术,主要采用了Go内置的模板引擎,最后我们介绍了一些辅助的日志、配置等信息的设计,通过这些设计我们实现了一个基础的框架beego,目前该框架已经开源在github,最后我们通过beego实现了一个博客系统,通过实例代码详细的展现了如何快速的开发一个站点。
|
||||
|
||||
## links
|
||||
* [目录](<preface.md>)
|
||||
* 上一章: [数据库操作](<13.5.md>)
|
||||
* 下一节: [小结](<13.7.md>)
|
||||
* 上一章: [实现博客的增删改](<13.5.md>)
|
||||
* 下一节: [扩展博客管理系统](<14.md>)
|
||||
6
13.7.md
6
13.7.md
@@ -1,6 +0,0 @@
|
||||
# 13.7 小结
|
||||
|
||||
## links
|
||||
* [目录](<preface.md>)
|
||||
* 上一章: [实现博客的增删改](<13.6.md>)
|
||||
* 下一节: [扩展博客管理系统](<14.md>)
|
||||
15
13.md
15
13.md
@@ -1,16 +1,15 @@
|
||||
# 13 构建博客系统
|
||||
前面十二章介绍了如何通过Go来开发Web应用,介绍了很多基础知识、开发工具和开发技巧,那么我们这一章通过这些知识来实现一个简易的博客系统。通过Go语言来实现一个完整的项目,这项目中主要内容有第一小节介绍的项目的结构规划,例如采用MVC模式来进行开发,程序的执行流程设计等内容;第二小节介绍博客系统的一些数据库结构设计,如何存储博客评论之类的信息;第三小节介绍项目的第一个功能:路由,如何让访问的URL映射到相应的处理逻辑;第四小节介绍处理逻辑,如何设计一个公共的controller,对象继承之后处理函数中如何处理response和request;第五小节介绍如何处理业务逻辑的数据库,这里会采用beedb库进行数据库的操作;第六小节介绍整体的博客的发表、修改、删除、显示列表等操作。
|
||||
# 13 如何设计一个Web框架
|
||||
前面十二章介绍了如何通过Go来开发Web应用,介绍了很多基础知识、开发工具和开发技巧,那么我们这一章通过这些知识来实现一个简易的Web框架。通过Go语言来实现一个完整的框架设计,这框架中主要内容有第一小节介绍的Web框架的结构规划,例如采用MVC模式来进行开发,程序的执行流程设计等内容;第二小节介绍框架的第一个功能:路由,如何让访问的URL映射到相应的处理逻辑;第三小节介绍处理逻辑,如何设计一个公共的controller,对象继承之后处理函数中如何处理response和request;第四小节介绍如何框架的一些辅助功能,例如日志处理、配置信息等;第五小节介绍如何基于Web框架实现一个博客,包括博文的发表、修改、删除、显示列表等操作。
|
||||
|
||||
通过这么一个完整的项目例子,我期望能够让读者了解如何开发Web应用,如何搭建自己的目录结构,如何实现路由,如何实现MVC模式等各方面的开发内容。在框架盛行的今天,MVC也不再是神话。经常听到很多程序员讨论哪个框架好,哪个框架不好, 其实框架只是工具,没有好与不好,只有适合与不适合,适合自己的就是最好的,所以教会大家自己动手写框架,那么不同的需求都可以用自己的思路去实现。
|
||||
|
||||
## 目录
|
||||
* 1 [项目规划](13.1.md)
|
||||
* 2 [数据库设计](13.2.md)
|
||||
* 3 [自定义路由器设计](13.3.md)
|
||||
* 4 [controller设计](13.4.md)
|
||||
* 5 [日志和配置设计](13.5.md)
|
||||
* 6 [实现博客的增删改](13.6.md)
|
||||
* 7 [小结](13.7.md)
|
||||
* 2 [自定义路由器设计](13.2.md)
|
||||
* 3 [controller设计](13.3.md)
|
||||
* 4 [日志和配置设计](13.4.md)
|
||||
* 5 [实现博客的增删改](13.5.md)
|
||||
* 6 [小结](13.6.md)
|
||||
|
||||
## links
|
||||
* [目录](<preface.md>)
|
||||
|
||||
11
preface.md
11
preface.md
@@ -78,12 +78,11 @@
|
||||
- 12.5 [小结](12.5.md)
|
||||
* 13.[构建博客系统](13.md)
|
||||
- 13.1 [项目规划](13.1.md)
|
||||
- 13.2 [数据库设计](13.2.md)
|
||||
- 13.3 [自定义路由器设计](13.3.md)
|
||||
- 13.4 [controller设计](13.4.md)
|
||||
- 13.5 [日志和配置设计](13.5.md)
|
||||
- 13.6 [实现博客的增删改](13.6.md)
|
||||
- 13.7 [小结](13.7.md)
|
||||
- 13.2 [自定义路由器设计](13.2.md)
|
||||
- 13.3 [controller设计](13.3.md)
|
||||
- 13.4 [日志和配置设计](13.4.md)
|
||||
- 13.5 [实现博客的增删改](13.5.md)
|
||||
- 13.6 [小结](13.6.md)
|
||||
* 14.扩展博客管理系统
|
||||
- 14.1 博客系统集成bootstrap
|
||||
- 14.2 博客集成留言功能
|
||||
|
||||
Reference in New Issue
Block a user