Beego学习笔记

Beego学习笔记 Go

路由(Controller)
路由就是根据用户的请求找到需要执行的函数或者controller。
Get /v1/shop/nike ShopController Get Delete /v1/shop/nike ShopController Delete Get /v1/notallowed notallowed function

beego路由类型
1:函数级别的注册RESTFul的方式注册
2:controller级别的注册自动化映射
3:更自由化的handler注册,即只需要实现了ServerHTTP(respose, request)函数都可以
函数级别的路由函数支持如下:
beego.Get(router, beego.FilterFunc) beego.Post(router, beego.FilterFunc) beego.Put(router, beego.FilterFunc) beego.Head(router, beego.FilterFunc) beego.Options(router, beego.FilterFunc) beego.Delete(router, beego.FilterFunc) beego.Any(router, beego.FilterFunc)

基础路由函数代码示例
基础GET请求
beego.Get("/", func(ctx *context.Context) { ctx.Output.Body([]byte("Hello, world!")) })

基础POST请求
beego.Post("/foo", func(ctx *context.Context) { ctx.Output.Body([]byte("bar")) })

任意HTTP请求
beego.Any("/alice", func(ctx *context.Context) { ctx.Output.Body([]byte("boo")) })

基础路由之Controller
beego最初的设计理念来源于tornado,即RESTFul的Controller实现
  • beego.Router(router, controller) 注册函数
type ObjectController struct{ beego.Controller //继承默认的beego.Controller } func (self *ObjectController) Get() { //复写get方法 obs := models.GetAll() self.Data["json"] = obs self.ServeJson() } beego.Router("/object", &ObjectController{})

参数路由
这个参数路由适用于函数和controller设置,解析之后的数据全部可以在ctx.Input.Param()获取。
为了用户更加方便的路由设置,beego参考了sintra的路由实现,支持多种方式的路由.
beego.Router("/api/:id", &controllers.RController{}) //默认匹配//匹配 /api/123 :id=123 可以匹配到/api/ 这个URL地址 beego.Router("/api/:id!", &controllers.RController{}) //默认匹配 //匹配 /api/123 :id=123 不能够匹配到/api/ 这个URL地址 beego.Router("/api/:id([0-9]+)", &controllers.RController{}) //自定义正则匹配 //匹配 /api/123 :id=123

beego.Router("/news/:all", &controllers.RController{}) //全匹配方式 //匹配 /news/path/to/123.html :all=path/to/123.html beego.Router("/user/:username([\w]+)", &controllers.RController{}) //正则字符串匹配 //匹配 /user/skymyyang :username=skymyyang beego.Router("/download/*.*", &controllers.RController{}) //*匹配方式 //匹配 /download/file/api.xml :path=file/api :ext=xml beego.Router("/download/ceshi/*", &controllers.RController{}) //*全匹配方式 //匹配 /download/ceshi/file/api.json :splat=file/api.json

beego.Router("/id:int", &controllers.RController{}) //int类型设置方式 匹配:id为int类型, 框架帮你实现了正则([0-9]+) beego.Router("/:hi:string", &controllers.RController{}) //string 类型设置方式 匹配:hi为string类型。框架帮你实现了正则([\w]+) beego.Router("/cms_:id([0-9]+).html", &controllers.RController{}) //带有前缀的自定义正则 //匹配 :id为正则类型。匹配cms_123.html这样的url :id=123

映射路由
以下是一个RESTFul的设计示例
beego.Router("/api/list", &RestController{}, "*:ListFood") //这里的*代表any的意思 beego.Router("/api/create", &RestController{}, "post:CreateFood") //post方法 beego.Router("/api/update", &RestController{}, "put:UpdateFood") //put方法 beego.Router("/api/delete", &RestController{}, "delete:DeleteFood") //delete方法

【Beego学习笔记】以下是多个HTTP Method指向同一个函数的示例:
beego.Router("/api", &RestController{}, "get,post:ApiFunc")

以下是不同的method对应不同的函数,通过“; ”进行分割的示例:
beego.Router("/simple", &SimpleController{}, "get:GetFunc; post:PostFunc")

可以用的HTTP Method如下:
  • *:包含以下所有的函数
  • get: GET请求
  • post:POST请求
  • put: PUT请求
  • delete: DELETE请求
  • patch: PATCH请求
  • options:OPTIONS请求
  • head:HEAD请求
如果同时存在*和对应的HTTP Method,那么将优先执行HTTP Method的方法,例如同时注册了如下所示的路由:
beego.Router("/simple", &SimpleController{}, "*:AllFunc; post:PostFunc")

自动化路由
beego.AutoRouter(&controllers.ObjectController{})

请求的影响如下:
/object/login 调用ObjectController中的 Login方法 /object/logout 调用ObjectController中的Logout方法

除了前缀/:controller/:method匹配之外,剩下的url beego会帮你自动化解析为参数,保存在this.Ctx.Input.Param当中:
/object/blog/2013/09/12 调用ObjectController中的blog方法,参数如下:map[0:2013 1:09 2:12]

方法名在内部是保存了用户设置的,例如Login,URL匹配的时候都会转化为小写,所以/object/LOGIN这样的URL也一样可以路由到用户定义的Login中。
自动化路由之API模式解析
现在已经可以通过自动识别出来下面类似的所有URL,都会吧请求分发到controller的simple方法:
/controller/simple /controller/simple.html /controller/simple.json /controller/simple.rss

可以通过this.Ctx.Input.Param(":ext")获取后缀名。
Namespace的路由设置
这个主要是在看了两个框架sinatra和laravel的使用方式之后进行的设计和开发
ns := beego.NewNamespace("/v1").Filter("before", auth).Get("/notallowed", func (ctx *context.Context){ ctx.Output.Body([]byte("notAllowed")) }).Router("/version", &AdminController{}, "get:ShowAPIVersion"). Router("/changepassword", &UserController{}). Namespace( beego.NewNamespace("/shop"). Filter("before", sentry). Get("/:id", func (ctx *context.Context){ ctx.Output.Body([]byte("notAllowed")) }), )//链式写的方法

namespace接口详解
  • NewNamespace(prefix string)
    初始化namespace对象,下面这些函数都是namespace对象的方法
  • Cond(cond namespaceCond)
    支持满足条件的就执行该namespace,不满足就不执行,例如你可以根据域名来控制namespace
    ns := NewNamespace("/v1") ns.Cond(func (ctx *context.Context) bool { if ctx.Input.Domain() == "api.beego.me"{ return true } return false })

  • Filter(action string, filter FilterFunc)
    action表示你需要执行的位置,before和after分别表示执行逻辑之前和执行逻辑之后的filter
  • Router(rootpath string, c ControllerInterface, mappingMethods ...strings)
  • AutoRouter(c ControllerInterface)
  • AutoPrefix(prefix string, c ControllerInterface)
  • Get(rootpath string, f FilterFunc)
  • Post(rootpath string, f FilterFunc)
  • Delete(rootpath string, f FilterFunc)
  • Put(rootpath string, f FilterFunc)
  • Head(rootpath string, f FilterFunc)
  • Options(rootpath string, f FilterFunc)
  • Patch(rootpath string, f FilterFunc)
  • Any(rootpath string, f FilterFunc)
  • Handler(rootpath string, h http.Handler) //还有第三个参数,是否前缀匹配,bool值
    以上这些都是设置路由的函数,详细的使用和前面beego的路由函数是一样的
    嵌套其他namespace
    Namespace(ns *Namespace)
ns := beego.NewNamespace("/v1"). Namespace( beego.NewNamespace("/shop"). Get(":id", func (ctx *context.Context){ ctx.Output.Body([]byte("shopinfo")) }), beego.NewNamespace("/order"). Get(":id",func (ctx *context.Context){ ctx.Output.Body([]byte("orderinfo")) }), beego.NewNamespace("/crm"). Get("/:id", func (ctx *context.Context){ ctx.Output.Body([]byte("crminfo")) }), )

如何规划项目的路由
1:简单的应用采用routers/router.go
2:多模块的采用namespace,然后引用的地方注册
beego.AddNamespace(ns)
3:目录
| -- beeapi | -- conf |`-- app.conf | -- controllers |`-- default.go | -- main.go | -- models |`-- object.go | -- routers |` -- router.go `-- tests `--default_test.go

参数设置
默认参数
1:AppName
应用名称,默认是beego,通过bee new创建的是创建的项目名。

2:AppPath
当前应用的路径,默认会通过设置os.Args[0]获得执行的命令的第一个参数,所以你在使用supervisor管理进程的时候记得

3:AppConfigPath
配置文件所在的路径,默认是应用程序对应目录下的conf/app.conf,用户可以修改该值配置自己的配置文件。

4:EnableHttpListen
是否启用HTTP监听,默认是true

5:HttpAddr
应用监听地址,默认为空,监听所有的网卡IP。

6:HttpPort
应用监听端口,默认为8080.

7:EnableHttpTLS
是否启用HTTPS,默认是关闭。

8:HttpsPort
应用监听https端口,默认为10443

9:HttpCertFile
开启HTTPS之后,certfile的路径。

10:HttpKeyFile
开启HTTPS之后,keyfile的路径

11:HttpServerTimeOut
设置http的超时时间,默认是0,不超时

12:RunMode
应用的模式,默认是dev,为开发模式,在开发模式下出错会提示友好的错误页面。

13:AtuoRender
是否模板自动渲染,默认值为true,对于API类型的应用,应该把该选项设置为false,不需要渲染模板。

14:ReciverPanic
是否异常恢复,默认值为true,即当应用出现异常的情况,通过recover恢复回来,而不会导致应用程序退出。

15:ViewsPath
模板路径,默认是views。

16:SessionOn
session 是否开启,默认是false。

17:SessionProvider
session 的引擎,默认是memory。

18:SessionName
存在客户端的 cookie名称,默认值是beegosessionID

19:SessionGCMaxLifetime
session 过期时间,默认值是3600秒。

20:SessionSavePath
session 保存路径,默认是空。

21:SessionHashFunc
sessionID生成函数,默认是sha1.

22:SessionHashKey
session hash 的key。

23:SessionCookieLifeTime
seesion默认存在客户端的cookie的时间,默认值是3600秒。

24:UseFcgi
是否启用fastcgi,默认是false。

25:MaxMemory
文件上传默认内存缓存大小,默认值是1 << 26(64M).

26:EnableGzip
是否开启gzip支持,默认为false,不支持gzip,一旦开启了gzip,那么在模板输出的内容会进行gzip或者zlib压缩。

27:DirectoryIndex
是否开启静态目录的列表显示,默认不显示目录,返回403错误。

28:BeegoServerName
beego 服务器默认在请求的时候输出 server为beego。

29:EnableAdmin
是否开启进程内监控模块,默认关闭。

30:AdminHttpAddr
监控程序监听的地址,默认值是 localhost。

31:AdminHttpPort
监控程序监听的端口,默认是8088.

32:TemplateLeft
模板左标签,默认值是{{。

33:TemplateRight
模板右标签,默认值是}}。

34:ErrorShow
是否显示错误,默认显示错误信息。

35:XSRFKEY
XSRF的key信息,默认值是beegoxsrf。

36:XSRFExpire
XSRF过期时间,默认值是0.

37:FlashName
Flash数据设置时Cookie的名称,默认是BEEGO_FLASH.

38:FlashSeperator
Flash数据的分隔符,默认是BEEGOFLASH。

39:StaticDir
静态文件目录设置,默认是static。

app.conf的说明
以上所有的配置都可以在app.conf里面进行设置,app.conf是ini解析。
[section] key = value beego.AppConfig.Bool("key") //读取key的value

控制器
控制器的设计
转载于:https://www.cnblogs.com/skymyyang/p/8023429.html

    推荐阅读