Go语言Web框架Tango在Session中间件中的设计

xiaolunwen · · 3151 次点击 · 开始浏览    置顶
这是一个创建于 的主题,其中的信息可能已经有所发展或是发生改变。

Tango在创建之初的目标就是既有Beego的效率,又有martini的灵活中间件。因此Session也是在核心库 [tango](https://github.com/lunny/tango) 之外作为官方中间件存在,地址是 [tango-session](https://github.com/tango-contrib/session)。 Session因为有着灵活的设计,因此可以完成很多我们希望的功能。首先看下Session中间件的选项: ```Go type Options struct { MaxAge time.Duration SessionIdName string Store Store Generator IdGenerator Tracker Tracker OnSessionNew func(*Session) OnSessionRelease func(*Session) } ``` 其中我将要着重讲的是Store,Generator和Tracker。 ## Store Store是一个接口,主要作用是存储Session中的内容,其定义如下: ```Go type Store interface { Add(id Id) bool Exist(id Id) bool Clear(id Id) bool Get(id Id, key string) interface{} Set(id Id, key string, value interface{}) error Del(id Id, key string) bool SetMaxAge(maxAge time.Duration) SetIdMaxAge(id Id, maxAge time.Duration) Run() error } ``` 默认的内核自带了`MemoryStore`,这将会把所有Session内容保存在内存中。同时官方中间件中也提供了 * [nodb](http://github.com/tango-contrib/session-nodb) * [redis](http://github.com/tango-contrib/session-redis) * [ledis](http://github.com/tango-contrib/session-ledis) * [ssdb](http://github.com/tango-contrib/session-ssdb) 这几种方式进行Session内容的存储。当然如果你愿意,也可以自己来实现一个Store。 ## Generator Generator是一个接口,主要封装了SessionID的生成算法,其定义如下: ```Go type IdGenerator interface { Gen(req *http.Request) Id IsValid(id Id) bool } ``` 默认的Generator是Sha1Generator,他是通过`req.RemoteAddr`,当前时间和随机字符串生成。 当然你也可以自定义更好的算法来生成SessionID。 ## Tracker Tracker是一个接口,主要封装了Session的跟踪方式,其定义如下: ```Go type Tracker interface { SetMaxAge(maxAge time.Duration) Get(req *http.Request) (Id, error) Set(req *http.Request, rw http.ResponseWriter, id Id) Clear(rw http.ResponseWriter) } ``` 默认的Tracker实现是`CookieTracker`,就是我们最常见的,将SessionID保存在cookie中,通过cookie来进行跟踪。Session中间件中也同时提供了`HeaderTracker`,支持将SessionID保存在自定义的Http Header中。当然你也可以自定义Tracker,比如通过URL参数来进行跟踪等等方式。 ## 最后 看起来似乎很复杂,但是一般情况下都不需要去改变,你只需要 ```Go t := tango.Classic() t.Use(session.New()) t.Run() ```

有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

3151 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传