入口
api := iris.New()
api.Adapt(gm.NewSession())
session的构造
1func NewSession() sessions.Sessions { 2db := redis.New(rs.Config{Network: rs.DefaultRedisNetwork, 3Addr: config.Instance().Redis.Address, 4Password: config.Instance().Redis.Password, 5Database: "", 6MaxIdle: 0, 7MaxActive: 0, 8IdleTimeout: rs.DefaultRedisIdleTimeout, 9Prefix: "", 10MaxAgeSeconds: config.Instance().Redis.MaxAgeSeconds}) // optionally configure the bridge between your redis server 11 12mySessions := sessions.New(sessions.Config{Cookie: configs.GetSessionConfig().Cookie, Expires: configs.GetSessionConfig().Expires}) 13mySessions.UseDatabase(db) 14return mySessions 15}
MaxAgeSeconds //指的是session在数据库存的有效期
Expires //指的是session的有效期
回到刚才的api.Adapt(gm.NewSession()),装饰器
1func (s *sessions) Adapt(frame *iris.Policies) { 2// for newcomers this maybe looks strange: 3// Each policy is an adaptor too, so they all can contain an Adapt. 4// If they contains an Adapt func then the policy is an adaptor too and this Adapt func is called 5// by Iris on .Adapt(...) 6policy := iris.SessionsPolicy{ 7Start: s.Start, 8Destroy: s.Destroy, 9} 10 11policy.Adapt(frame)
1func (s SessionsPolicy) Adapt(frame *Policies) { 2 if s.Start != nil { 3 frame.SessionsPolicy.Start = s.Start 4 } 5 if s.Destroy != nil { 6 frame.SessionsPolicy.Destroy = s.Destroy 7 } 8}
使用
调用context.Session(),获取到session对象
1func (ctx *Context) Session() Session { 2 policy := ctx.framework.policies.SessionsPolicy 3 if policy.Start == nil { 4 ctx.framework.Log(DevMode, 5 errSessionsPolicyIsMissing.Format(ctx.RemoteAddr(), ctx.framework.Config.VHost).Error()) 6 return nil 7 } 8 9 if ctx.session == nil { 10 ctx.session = policy.Start(ctx.ResponseWriter, ctx.Request) 11 } 12 13 return ctx.session 14}
如果session==nil,就会调用start
1func (s *sessions) Start(res http.ResponseWriter, req *http.Request) iris.Session { 2 var sess iris.Session 3 4 cookieValue := GetCookie(s.config.Cookie, req) 5 6 if cookieValue == "" { // cookie doesn't exists, let's generate a session and add set a cookie 7 sid := SessionIDGenerator(s.config.CookieLength) 8 9 sess = s.provider.Init(sid, s.config.Expires) 10 cookie := &http.Cookie{} 11 12 // The RFC makes no mention of encoding url value, so here I think to encode both sessionid key and the value using the safe(to put and to use as cookie) url-encoding 13 cookie.Name = s.config.Cookie 14 15 cookie.Value = sid 16 cookie.Path = "/" 17 if !s.config.DisableSubdomainPersistence { 18 19 requestDomain := req.URL.Host 20 if portIdx := strings.IndexByte(requestDomain, ':'); portIdx > 0 { 21 requestDomain = requestDomain[0:portIdx] 22 } 23 if IsValidCookieDomain(requestDomain) { 24 25 // RFC2109, we allow level 1 subdomains, but no further 26 // if we have localhost.com , we want the localhost.cos. 27 // so if we have something like: mysubdomain.localhost.com we want the localhost here 28 // if we have mysubsubdomain.mysubdomain.localhost.com we want the .mysubdomain.localhost.com here 29 // slow things here, especially the 'replace' but this is a good and understable( I hope) way to get the be able to set cookies from subdomains & domain with 1-level limit 30 if dotIdx := strings.LastIndexByte(requestDomain, '.'); dotIdx > 0 { 31 // is mysubdomain.localhost.com || mysubsubdomain.mysubdomain.localhost.com 32 s := requestDomain[0:dotIdx] // set mysubdomain.localhost || mysubsubdomain.mysubdomain.localhost 33 if secondDotIdx := strings.LastIndexByte(s, '.'); secondDotIdx > 0 { 34 //is mysubdomain.localhost || mysubsubdomain.mysubdomain.localhost 35 s = s[secondDotIdx+1:] // set to localhost || mysubdomain.localhost 36 } 37 // replace the s with the requestDomain before the domain's siffux 38 subdomainSuff := strings.LastIndexByte(requestDomain, '.') 39 if subdomainSuff > len(s) { // if it is actual exists as subdomain suffix 40 requestDomain = strings.Replace(requestDomain, requestDomain[0:subdomainSuff], s, 1) // set to localhost.com || mysubdomain.localhost.com 41 } 42 } 43 // finally set the .localhost.com (for(1-level) || .mysubdomain.localhost.com (for 2-level subdomain allow) 44 cookie.Domain = "." + requestDomain // . to allow persistence 45 } 46 47 } 48 cookie.HttpOnly = true 49 // MaxAge=0 means no 'Max-Age' attribute specified. 50 // MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0' 51 // MaxAge>0 means Max-Age attribute present and given in seconds 52 if s.config.Expires >= 0 { 53 if s.config.Expires == 0 { // unlimited life 54 cookie.Expires = CookieExpireUnlimited 55 } else { // > 0 56 cookie.Expires = time.Now().Add(s.config.Expires) 57 } 58 cookie.MaxAge = int(cookie.Expires.Sub(time.Now()).Seconds()) 59 } 60 61 // encode the session id cookie client value right before send it. 62 cookie.Value = s.encodeCookieValue(cookie.Value) 63 64 AddCookie(cookie, res) 65 } else { 66 cookieValue = s.decodeCookieValue(cookieValue) 67 68 sess = s.provider.Read(cookieValue, s.config.Expires) 69 } 70 return sess 71}
再设置cookie.Domain的时候,req.URL作为服务端的时候,是没有Host信息的,所以cookie.Domain 会默认空串。
再看s.provider.Init
1// Init creates the session and returns it 2func (p *provider) Init(sid string, expires time.Duration) iris.Session { 3newSession := p.newSession(sid, expires) 4p.mu.Lock() 5p.sessions[sid] = newSession 6p.mu.Unlock() 7return newSession 8}
init的时候做了两件事:
1.newSession
2.将session存到p.sessions里面
1// newSession returns a new session from sessionid 2func (p *provider) newSession(sid string, expires time.Duration) *session { 3 4 sess := &session{ 5 sid: sid, 6 provider: p, 7 values: p.loadSessionValues(sid), 8 flashes: make(map[string]*flashMessage), 9 } 10 11 if expires > 0 { // if not unlimited life duration and no -1 (cookie remove action is based on browser's session) 12 time.AfterFunc(expires, func() { 13 // the destroy makes the check if this session is exists then or not, 14 // this is used to destroy the session from the server-side also 15 // it's good to have here for security reasons, I didn't add it on the gc function to separate its action 16 p.Destroy(sid) 17 }) 18 } 19 20 return sess 21}
这里可以看到在配置文件中设置的expire 是用来起了一个定时任务,之后删掉这个session
1func (p *provider) Destroy(sid string) { 2 p.mu.Lock() 3 if sess, found := p.sessions[sid]; found { 4 sess.values = nil 5 sess.flashes = nil 6 delete(p.sessions, sid) 7 p.updateDatabases(sid, nil) 8 } 9 p.mu.Unlock() 10}
destory的时候:
如果没有删除:
1.从p.sessions里面删除
2.更新到数据库
