Slide 1

Slide 1 text

beego: A Go Framework for Combination astaxie Head of Platform Engineering at Zalora beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 1 of 44 02/09/2014 12:21

Slide 2

Slide 2 text

Outline What's beego Beego Philosophy Quickstart Independent modules Plugins Useful Utils Use Cases More materials beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 2 of 44 02/09/2014 12:21

Slide 3

Slide 3 text

beego is A full stack, micro-framework for Go Easy to develop Easy to configure Loose coupling Well documented RESTFul router Namespace Testable Auto API documents beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 3 of 44 02/09/2014 12:21

Slide 4

Slide 4 text

Unix Philosophy Modularity: Write simple parts connected by clean interfaces Separation: Separate policy from mechanism; separate interfaces from engines Composition: Design programs to be connected to other programs The important rule less is more beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 4 of 44 02/09/2014 12:21

Slide 5

Slide 5 text

beego Philosophy it's all about combination beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 5 of 44 02/09/2014 12:21

Slide 6

Slide 6 text

beego Philosophy beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 6 of 44 02/09/2014 12:21

Slide 7

Slide 7 text

beego Philosophy beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 7 of 44 02/09/2014 12:21

Slide 8

Slide 8 text

beego Philosophy one micro core many modules attempted to combine the very best of what we have seen in other web frameworks: Flask, Rails, Sinatra providing powerful tools fast, fast, fast beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 8 of 44 02/09/2014 12:21

Slide 9

Slide 9 text

quickstart install bee tool go get github.com/beego/bee create an application bee new mygo beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 9 of 44 02/09/2014 12:21

Slide 10

Slide 10 text

modules beego is built upon independent modules that are loosely coupled: cache config context httplibs logs orm sessions toolbox validation beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 10 of 44 02/09/2014 12:21

Slide 11

Slide 11 text

beego Cache Supporting different kinds of Cache engine: memory, memcache, redis, file Using Gob for encoding and decoding internally 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 beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 11 of 44 02/09/2014 12:21

Slide 12

Slide 12 text

beego Cache Example func main() { c, err := cache.NewCache("memory", `{"interval":60}`) err = c.Put("nums", 12, 0) if err != nil { log.Fatal("err") } v := c.Get("nums") log.Println(v) c.Incr("nums") v = c.Get("nums") log.Println(v) c.Decr("nums") v = c.Get("nums") log.Println(v) c.Delete("nums") if c.IsExist("nums") { log.Fatal("delete err") } } Run beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 12 of 44 02/09/2014 12:21

Slide 13

Slide 13 text

beego Config Supporting different format of config files: 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 beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 13 of 44 02/09/2014 12:21

Slide 14

Slide 14 text

beego Config Example func main() { cnf, err := config.NewConfig("ini", "app.conf") if err != nil { log.Fatal(err) } log.Println(cnf.String("appname")) log.Println(cnf.DefaultInt("max", 1000)) log.Println(cnf.DefaultInt("min", 1000)) log.Println(cnf.String("demo::port")) cnf.Set("username", "astaxie") cnf.Set("section::username", "asta") cnf.SaveConfigFile("hello.conf") } Run beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 14 of 44 02/09/2014 12:21

Slide 15

Slide 15 text

beego Context The Context module based on HTTP request & response. Input: get input data. Implemented many useful methods by Request Query,Cookie,Ip,Refer,Header,Session,IsWebsocket... Output: The encapsulation for Response Header,Body,Cookie,Json,Jsonp,Xml,Download... Usage: The Ctx encapsulated in Controller is *context.Context object type Some struct { beego.Controller } func (this *Some) Get() { name := this.Ctx.Input.Query("name") m := models.GetUser(name) this.Ctx.Output.Json(m) } beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 15 of 44 02/09/2014 12:21

Slide 16

Slide 16 text

beego httplibs Used to simulate client to send out HTTP requests. like 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: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 16 of 44 02/09/2014 12:21

Slide 17

Slide 17 text

beego httplibs Example func Get() { req := httplib.Get("http://httpbin.org/get") resp, err := req.Response() if err != nil { log.Fatal(err) } log.Println(resp) } func Post() { req := httplib.Post("http://httpbin.org/post") req.Param("username", "astaxie") str, err := req.String() if err != nil { log.Fatal(err) } log.Println(str) } Run beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 17 of 44 02/09/2014 12:21

Slide 18

Slide 18 text

beego logs Supporting different kinds of 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: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 18 of 44 02/09/2014 12:21

Slide 19

Slide 19 text

beego logs Example func main() { log := logs.NewLogger(10000) log.SetLogger("console", "") log.EnableFuncCallDepth(true) // turn on the file & line log.Trace("trace %s %s", "param1", "param2") log.Debug("debug") log.Info("info") log.Warn("warning") log.Error("error") log.Critical("critical") time.Sleep(1 * 1e9) // why ? } Run beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 19 of 44 02/09/2014 12:21

Slide 20

Slide 20 text

beego orm Inspired by Django ORM and SQLAlchemy Supported databases and drivers MySQL:github.com/go-sql-driver/mysql PostgreSQL:github.com/lib/pq Sqlite3:github.com/mattn/go-sqlite3 Define model by struct: type User struct { Id int Name string `orm:"size(100)"` } beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 20 of 44 02/09/2014 12:21

Slide 21

Slide 21 text

beego orm features Chainable API Relations Struct <-> Table Mapping Supporting all the Go's type Using simple CRUD style Auto creating tables. Auto Join association tables Crossing databse compatibility check Can use raw SQL for querying and mapping Fully coverd test cases to keep the ORM stable and robust beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 21 of 44 02/09/2014 12:21

Slide 22

Slide 22 text

beego orm basic CRUD type User struct { Id int64 Birthday time.Time Age int64 Name string CreatedAt time.Time `orm:"auto_now_add;type(datetime)"` UpdatedAt time.Time `orm:"auto_now;type(datetime)"` } func init() { orm.RegisterModel(new(User)) orm.RegisterDataBase("default", "mysql", "root:@/test?charset=utf8&loc=Asia%2FShanghai") } Run beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 22 of 44 02/09/2014 12:21

Slide 23

Slide 23 text

beego orm basic CRUD more Example: http://beego.me/docs/mvc/model/overview.md func main() { o := orm.NewOrm() user := new(User) user.Name = "astaxie" fmt.Println(o.Insert(user)) fmt.Println(user) user.Name = "asta" fmt.Println(o.Update(user)) fmt.Println(user) fmt.Println(o.Read(user)) fmt.Println(user) fmt.Println(o.Delete(user)) fmt.Println(user) } Run beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 23 of 44 02/09/2014 12:21

Slide 24

Slide 24 text

beego sessions Session module is used to store user data between different requests. you can use many session providers, including cookie, memory, file, redis, memcache, PostgreSQL, MySQL, and couchbase. initialize the seesion Manager: func init() { globalSessions, _ = session.NewManager("memory", `{"cookieName":"gosessionid", "gclifetime":3600, "cookieLifeTime": 3600}`) go globalSessions.GC() } After Session enabled: ss:= globalSessions.SessionStart(w, r) ss.GetSession(key) ss.SetSession(key, value) ss.Delete(key) ss.SessionID() beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 24 of 44 02/09/2014 12:21

Slide 25

Slide 25 text

beego toolbox Inspired by Dropwizard framework Here are the features: healthcheck profile statistics task beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 25 of 44 02/09/2014 12:21

Slide 26

Slide 26 text

beego toolbox Example beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 26 of 44 02/09/2014 12:21

Slide 27

Slide 27 text

beego 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 := validation.Validation{} valid.Required(u.Name, "name") valid.MaxSize(u.Name, 15, "nameMax") valid.Range(u.Age, 0, 140, "age") if valid.HasErrors() { for _, err := range valid.Errors { log.Println(err.Key, err.Message) } } if v := valid.Max(u.Age, 140, "age"); !v.Ok { log.Println(v.Error.Key, v.Error.Message) } } Run beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 27 of 44 02/09/2014 12:21

Slide 28

Slide 28 text

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 := validation.Validation{} u := user{Name: "test", Age: 40} b, err := valid.Valid(u) if err != nil { // handle error } if !b { // validation does not pass // blabla... } } Run beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 28 of 44 02/09/2014 12:21

Slide 29

Slide 29 text

planning developing testing blueprint Zero-downtime beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 29 of 44 02/09/2014 12:21

Slide 30

Slide 30 text

Plugins apiauth auth cors gorelic pongo2 beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 30 of 44 02/09/2014 12:21

Slide 31

Slide 31 text

beego apiauth Signing and Authenticating REST Requests, Inspired from AWS API AUTH. import( "github.com/astaxie/beego" "github.com/astaxie/beego/plugins/apiauth" ) func main(){ // apiauth every request beego.InsertFilter("*", beego.BeforeRouter,apiauth.APIBaiscAuth("appid","appkey")) beego.Run() } more documents: http://godoc.org/github.com/astaxie/beego/plugins/apiauth beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 31 of 44 02/09/2014 12:21

Slide 32

Slide 32 text

beego auth basic auth for api access: import( "github.com/astaxie/beego" "github.com/astaxie/beego/plugins/auth" ) func main(){ // authenticate every request beego.InsertFilter("*", beego.BeforeRouter,auth.Basic("username","secretpassword")) beego.Run() } more documents: http://godoc.org/github.com/astaxie/beego/plugins/auth beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 32 of 44 02/09/2014 12:21

Slide 33

Slide 33 text

beego cors cors provides handlers to enable CORS support import ( "github.com/astaxie/beego" "github.com/astaxie/beego/plugins/cors" ) func main() { // CORS for https://foo.* origins, allowing: // - PUT and PATCH methods // - Origin header // - Credentials share beego.InsertFilter("*", beego.BeforeRouter,cors.Allow(&cors.Options{ AllowOrigins: []string{"https://*.foo.com"}, AllowMethods: []string{"PUT", "PATCH"}, AllowHeaders: []string{"Origin"}, ExposeHeaders: []string{"Content-Length"}, AllowCredentials: true, })) beego.Run() } more documents: http://godoc.org/github.com/astaxie/beego/plugins/cors beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 33 of 44 02/09/2014 12:21

Slide 34

Slide 34 text

beego gorelic beego_gorelic is NewRelic middleware for beego framework. func main(){ beego_gorelic.InitNewrelicAgent() beego.Run() } more documents: https://github.com/yvasiyarov/beego_gorelic beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 34 of 44 02/09/2014 12:21

Slide 35

Slide 35 text

beego pongo2 A tiny little helper for using Pongo2 with Beego. import ( "github.com/astaxie/beego" "github.com/oal/beego-pongo2" ) type MainController struct { beego.Controller } func (this *MainController) Get() { pongo2.Render(this.Ctx, "page.html", pongo2.Context{ "ints": []int{1, 2, 3, 4, 5}, }) } more documents: https://github.com/oal/beego-pongo2 beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 35 of 44 02/09/2014 12:21

Slide 36

Slide 36 text

planning developing auth2 RBAC ACL request data filter beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 36 of 44 02/09/2014 12:21

Slide 37

Slide 37 text

Useful Utils captcha mail debug safemap slice utils file utils beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 37 of 44 02/09/2014 12:21

Slide 38

Slide 38 text

Use Cases beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 38 of 44 02/09/2014 12:21

Slide 39

Slide 39 text

Summary beego is production ready battle tested high perfomence robust stable active and supportive community beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 39 of 44 02/09/2014 12:21

Slide 40

Slide 40 text

Resource Beego offical site beego.me (beego.me) beego.me/docs/intro/ (beego.me/docs/intro/) github.com/beego (github.com/beego) other modules: i18n social-auth beego compress beego admin beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 40 of 44 02/09/2014 12:21

Slide 41

Slide 41 text

Tutorial Building Web Applications with Beego www.sitepoint.com/go-building-web-applications-beego/ (http://www.sitepoint.com/go-building-web-applications- beego/) www.sitepoint.com/go-building-web-applications-beego-part-2/ (http://www.sitepoint.com/go-building- web-applications-beego-part-2/) Web Application Using Beego and Mgo www.goinggo.net/2013/12/sample-web-application-using-beego-and.html (http://www.goinggo.net /2013/12/sample-web-application-using-beego-and.html) Go Advent Day 5 - An introduction to beego blog.gopheracademy.com/day-05-beego (http://blog.gopheracademy.com/day-05-beego) QCon 2013 Build high performance API with Beego djt.qq.com/ppt/236 beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 41 of 44 02/09/2014 12:21

Slide 42

Slide 42 text

Open source project based on beego WebSite: github.com/beego/beeweb (https://github.com/beego/beeweb) github.com/Unknwon/gowalker (https://github.com/Unknwon/gowalker) blogs: github.com/UlricQin/beego-blog (https://github.com/UlricQin/beego-blog) github.com/lisijie/goblog (https://github.com/lisijie/goblog) cms github.com/insionng/toropress (https://github.com/insionng/toropress) beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 42 of 44 02/09/2014 12:21

Slide 43

Slide 43 text

Open source project based on beego bbs github.com/beego/wetalk (https://github.com/beego/wetalk) APP Store Server github.com/typecho-app-store/typecho-app-store (https://github.com/typecho-app-store/typecho-app-store) beego-mgo github.com/goinggo/beego-mgo (https://github.com/goinggo/beego-mgo) beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 43 of 44 02/09/2014 12:21

Slide 44

Slide 44 text

Thank you 16:00 16 July 2014 (#ZgotmplZ) Tags: Go (#ZgotmplZ) astaxie Head of Platform Engineering at Zalora http://github.com/astaxie (http://github.com/astaxie) http://twitter.com/astaxie (http://twitter.com/astaxie) http://sg.linkedin.com/pub/asta-xie/57/59/ba2/ (http://sg.linkedin.com/pub/asta-xie/57/59/ba2/) beego: A Go Framework for Combination http://10.1.32.252:3999/Go/beego.slide 44 of 44 02/09/2014 12:21