beego 设计理念与API开发
ECUG技术分享
Asta Xie
大纲
什么是beego
beego的设计理念
模块化
插件化
API开发
beego快速开发演示
1 of 22 12/15/14, 8:10 PM
什么是beego
简单核心,丰富库的框架
松耦合
文档丰富
RESTFul以及强大的路由功能
自由而强大的Namespace
自动化的API文档功能
强大的开发工具
用户案例
2 of 22 12/15/14, 8:10 PM
Unix设计理念
模块化: Write simple parts connected by clean interfaces
分离: Separate policy from mechanism; separate interfaces from engines
组合: Design programs to be connected to other programs
最重要的规则:
less is more
beego 设计理念
3 of 22 12/15/14, 8:10 PM
beego 设计理念
beego 设计理念
4 of 22 12/15/14, 8:10 PM
beego 设计理念
简单的内核
丰富的模块
学习其他成功框架的库: Flask, Rails, Sinatra
提供强大的开发工具
插件化设计
fast, fast, fast
快速演示
安装bee工具
go get
创建一个应用
bee new mygo
5 of 22 12/15/14, 8:10 PM
模块化和组合的理念
beego是基于各个独立模块的一个框架,主要的模块如下:
cache
config
context
httplibs
logs
orm
sessions
toolbox
validation
Cache 设计
支持各种不同的引擎:
memory, memcache, redis, file
内部所有的数据使用Gob来进行编解码
interface:
Get(key string) interface{}
Put(key string, val interface{}, timeout int64) error
Delete(key string) error
Incr(key string) error
Decr(key string) error
IsExist(key string) bool
ClearAll() error
StartAndGC(config string) error
6 of 22 12/15/14, 8:10 PM
beego Cache Example
func main() {
c, err := ("memory", `{"interval":60}`)
err = ("nums", 12, 0)
if err != nil {
("err")
}
v := ("nums")
(v)
("nums")
v = ("nums")
(v)
("nums")
v = ("nums")
(v)
("nums")
if ("nums") {
("delete err")
}
} Run
Config 设计
支持各种不同的解析引擎:
ini, json, xml, yaml
interface:
Set(key, val string) error
String(key string) string
Strings(key string) []string
Int(key string) (int, error)
Int64(key string) (int64, error)
Bool(key string) (bool, error)
Float(key string) (float64, error)
DefaultString(key string, defaultval string) string
DefaultStrings(key string, defaultval []string) []string
DefaultInt(key string, defaultval int) int
DefaultInt64(key string, defaultval int64) int64
DefaultBool(key string, defaultval bool) bool
DefaultFloat(key string, defaultval float64) float64
DIY(key string) (interface{}, error)
GetSection(section string) (map[string]string, error)
SaveConfigFile(filename string) error
7 of 22 12/15/14, 8:10 PM
beego Config Example
func main() {
cnf, err := ("ini", "")
if err != nil {
(err)
}
(("appname"))
(("max", 1000))
(("min", 1000))
(("demo::port"))
("username", "astaxie")
("section::username", "asta")
("")
} Run
Context 设计
基于HTTP request & response的工具集
Input:
Query,Cookie,Ip,Refer,Header,Session,IsWebsocket...
Output:
Header,Body,Cookie,Json,Jsonp,Xml,Download...
Usage:
type Some struct {
}
func (this *Some) Get() {
name := ("name")
m := (name)
(m)
}
8 of 22 12/15/14, 8:10 PM
httplibs 设计
类似Python的httplib,用来模拟客户端请求
Supporting debug output
Supporting HTTPS request
Supporting timeout
Supporting request parameters
Supporting file uploading
Functions:
Get(url string)
Post(url string)
Put(url string)
Delete(url string)
Head(url string)
beego httplibs Example
func Get() {
req := ("
resp, err := ()
if err != nil {
(err)
}
(resp)
}
func Post() {
req := ("
("username", "astaxie")
str, err := ()
if err != nil {
(err)
}
(str)
} Run
9 of 22 12/15/14, 8:10 PM
logs 设计
支持各种引擎的日志:
console, conn, file, smtp
日志特性:
Different output writers:Console, File, SMTP, Conn
High perfomence
easy configuration and rapid deployment
Automatic log filtering based on log levels on a per-output basis
File logging with rotation (size, linecount, daily)
Global variables and functions for easy usage in standalone apps
beego logs Example
func main() {
log := (10000)
("console", "")
(true) // turn on the file & line
("trace %s %s", "param1", "param2")
("debug")
("info")
("warning")
("error")
("critical")
(1 * 1e9) // why ?
} Run
10 of 22 12/15/14, 8:10 PM
ORM 设计
Inspired by Django ORM and SQLAlchemy
目前支持的数据库
MySQL:
PostgreSQL:
Sqlite3:
结构定义:
type User struct {
Id int
Name string `orm:"size(100)"`
}
ORM 特性
链式API
支持数据关系
Struct <-> Table
支持所有的Go的类型
简单的CRUD风格
自动创建表.
自动关联创建
可以直接使用raw sql写
完整的测试代码
11 of 22 12/15/14, 8:10 PM
CRUD
type User struct {
Id int64
Birthday
Age int64
Name string
CreatedAt `orm:"auto_now_add;type(datetime)"`
UpdatedAt `orm:"auto_now;type(datetime)"`
}
func init() {
(new(User))
("default", "mysql", "root:@/test?charset=utf8&loc=Asia%2FShanghai")
} Run
CRUD
更多例子:
func main() {
o := ()
user := new(User)
= "astaxie"
((user))
(user)
= "asta"
((user))
(user)
((user))
(user)
((user))
(user)
} Run
12 of 22 12/15/14, 8:10 PM
sessions 设计
Session 模块支持各种引擎:
cookie, memory, file, redis, memcache, PostgreSQL, MySQL, and couchbase.
独立使用session模块,初始化:
func init() {
globalSessions, _ = ("memory",
`{"cookieName":"gosessionid", "gclifetime":3600, "cookieLifeTime": 3600}`)
go ()
}
应用中使用:
ss:= (w, r)
(key)
(key, value)
(key)
()
toolbox 设计
Inspired by Dropwizard framework
特性:
healthcheck
profile
statistics
task
13 of 22 12/15/14, 8:10 PM
toolbox Example
validation 设计
Validation is a data validation and error handling using Go.
type User struct {
Name string
Age int
}
func main() {
u := User{"man", 40}
valid := {}
(, "name")
(, 15, "nameMax")
(, 0, 140, "age")
if () {
for _, err := range {
(, )
}
}
if v := (, 140, "age"); ! {
(, )
}
} Run
14 of 22 12/15/14, 8:10 PM
beego validation Example
type user struct {
Id int
Name string `valid:"Required;Match(/^(test)?\\w*@;com$/)"`
Age int `valid:"Required;Range(1, 140)"`
}
func main() {
valid := {}
u := user{Name: "test", Age: 40}
b, err := (u)
if err != nil {
// handle error
}
if !b {
// validation does not pass
// blabla...
}
} Run
模块开发问题
testing
blueprint
Zero-downtime
15 of 22 12/15/14, 8:10 PM
插件化设计
apiauth
auth
cors
gorelic
pongo2
apiauth 插件
Inspired from AWS API AUTH. API的验证
import(
"
"
)
func main(){
// apiauth every request
("*", ,("appid","appkey"))
()
}
more documents:
16 of 22 12/15/14, 8:10 PM
auth 插件
basic auth :
import(
"
"
)
func main(){
// authenticate every request
("*", ,("username","secretpassword"))
()
}
more documents:
cors 插件
解决CORS问题
import (
"
"
)
func main() {
// CORS for https://foo.* origins, allowing:
// - PUT and PATCH methods
// - Origin header
// - Credentials share
("*", ,(&{
AllowOrigins: []string{"https://*."},
AllowMethods: []string{"PUT", "PATCH"},
AllowHeaders: []string{"Origin"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: true,
}))
()
}
more documents:
17 of 22 12/15/14, 8:10 PM
gorelic 插件
beego_gorelic is NewRelic middleware for beego framework.
func main(){
()
()
}
more documents:
pongo2 插件
A tiny little helper for using Pongo2 with Beego.
import (
"
"
)
type MainController struct {
}
func (this *MainController) Get() {
(, "", {
"ints": []int{1, 2, 3, 4, 5},
})
}
more documents:
18 of 22 12/15/14, 8:10 PM
插件开发计划
auth2
RBAC
ACL
Utils 库
captcha
mail
debug
safemap
slice utils
file utils
pagination
19 of 22 12/15/14, 8:10 PM
总结
组合框架
高度松耦合
interface和engine分离,容易扩展
模块丰富,product ready
插件设计,动态扩展系统
API开发
API变得越来越重要,因为容易扩展,松耦合
API开发关注的几个点:
RESTFul
文档
效率
容易维护
部署
20 of 22 12/15/14, 8:10 PM
Thank you
ECUG技术分享
10:00 14 Dec 2014 (#ZgotmplZ)
Tags: beego (#ZgotmplZ)
Asta Xie
(
(
(
22 of 22 12/15/14, 8:10 PM