beego是一个快速开发 Go 应用的 HTTP 框架,他可以用来快速开发 API、Web 及后端服务等各种应用,是一个 RESTful 的框架,主要设计灵感来源于 tornado、sinatra 和 flask 这三个框架,但是结合了 Go 本身的一些特性(interface、struct 嵌入等)而设计的一个框架。
1.1 核心模块
(1) Controller
- Beego 是一个典型的 MVC 框架 (Model-View-Controller)的,所以它定义了一个核心接口 ControllerInterface。 ControllerInterface 定义了一个控制器必须要解决什么问题(这些问题的方法定义)。
- 路由的主要功能是实现从请求地址到实现的方法,beego中封装了Controller,所以路由是从路径到ControllerInterface的过程,ControllerInterface的方法有如下:
// ControllerInterface is an interface to uniform all controller handler.
type ControllerInterface interface {
Init(ct *context.Context, controllerName, actionName string, app interface{})
Prepare()
Get()
Post()
Delete()
Put()
Head()
Patch()
Options()
Trace()
Finish()
Render() error
XSRFToken() string
CheckXSRFCookie() bool
HandlerFunc(fn string) bool
URLMapping()
}
复制代码
- Controller 为 ControllerInterface 的默认实现, 它提供了实现自定义控制器的各种辅助方法,所以在 Beego 里面,一般都是组合 Controller 来实现自己的 Controlle
type UserController struct {
web.Controller
}
type User struct {
Name string
}
func (c *UserController) GetUser() {
c.Ctx.WriteString(" hello Stone")
}
func (c *UserController) CreateUser() {
u := &User{}
err := c.Ctx.BindJSON(u)
if err != nil {
c.Ctx.WriteString(err.Error())
return
}
_ = c.Ctx.JSONResp(u)
}
复制代码
注意到用户虽然被要求组合 Controller,但是路由注册和服务器启动是通过另外一套机制来完成的。
(2) HttpServer
代表http服务器是服务器的抽象,大多时候就是一共进程,用于管理web应用的生命周期和资源隔离单位。
// HttpServer defines beego application with a new PatternServeMux.
type HttpServer struct {
Handlers *ControllerRegister
Server *http.Server
Cfg *Config
LifeCycleCallbacks []LifeCycleCallback
}
复制代码
(3) ControllerRegister
虽然路由是从路径到ControllerInterface的过程,但是在这过程中的注册路由,路由匹配和执行业务代码都是透过 ControllerRegiste 来完成的。
// ControllerRegister containers registered router rules, controller handlers and filters.
type ControllerRegister struct {
// 路由树
routers map[string]*Tree
enablePolicy bool
enableFilter bool
policies map[string]*Tree
filters [FinishRouter + 1][]*FilterRouter
pool sync.Pool
// the filter created by FilterChain
chainRoot *FilterRouter
// keep registered chain and build it when serve http
filterChains []filterChainConfig
cfg *Config
}
复制代码
(4) Context
用户操作请求和响应是通过 Ctx 来达成的。它代表的是整 个请求执行过程的上下文。Beego 将 Context 细分了几个部分:
- Input:定义了很多和处理请求有关的方法
- Output:定义了很多和响应有关的方法
- Response:对 http.ResponseWriter 的二次封装
1.2 总结
ControllerInterface 可以看做核心接口,因为它直接体现了Beego 的设计初衷:MVC 模式。同时它也是用户核心接入点。但是如果从功能特性上来说,HttpServer 和 ControllerRegister 才是核心。
- HttpServer 作为服务器抽象,用于管理应用生命周期和资源隔离单位。
- ControllerRegister 解决了路由注册和路由匹配问题。
- Context 和 Controller 为用户提供了丰富 API,用于辅助构建系统。
优点:
- 简单
- 性能良好,开发效率不错,解放开发者生产力
- 社区有很多中文开发者,找资料是相对方便的
- 代码文档化做的很好
缺点
- 比较臃肿,因为提供了很多支持,当遇到坑时需要花很多时间查源码解决问题
- 模块众多,这既是优点也是缺点