1
0
mirror of https://github.com/kataras/iris.git synced 2025-12-18 02:17:05 +00:00

minor version 11.2.2 - register sessions as middleware and Context.HTML/Text like Context.Writef

Former-commit-id: 6f5f1c502fb06d739c350c3ecc891f495dc03a6e
This commit is contained in:
Gerasimos (Makis) Maropoulos
2019-07-24 19:51:42 +03:00
parent 275cc14e39
commit 29bf846bd1
10 changed files with 95 additions and 39 deletions

View File

@@ -411,6 +411,11 @@ func (s *Session) Visit(cb func(k string, v interface{})) {
s.provider.db.Visit(s.sid, cb)
}
// Len returns the total number of stored values in this session.
func (s *Session) Len() int {
return s.provider.db.Len(s.sid)
}
func (s *Session) set(key string, value interface{}, immutable bool) {
s.provider.db.Set(s.sid, s.Lifetime, key, value, immutable)

View File

@@ -77,7 +77,7 @@ func (s *Sessions) updateCookie(ctx context.Context, sid string, expires time.Du
func (s *Sessions) Start(ctx context.Context, cookieOptions ...context.CookieOption) *Session {
cookieValue := s.decodeCookieValue(GetCookie(ctx, s.config.Cookie))
if cookieValue == "" { // cookie doesn't exists, let's generate a session and add set a cookie
if cookieValue == "" { // cookie doesn't exist, let's generate a session and set a cookie.
sid := s.config.SessionIDGenerator(ctx)
sess := s.provider.Init(sid, s.config.Expires)
@@ -88,9 +88,35 @@ func (s *Sessions) Start(ctx context.Context, cookieOptions ...context.CookieOpt
return sess
}
sess := s.provider.Read(cookieValue, s.config.Expires)
return s.provider.Read(cookieValue, s.config.Expires)
}
return sess
const contextSessionKey = "_iris_session"
// Handler returns a sessions middleware to register on application routes.
func (s *Sessions) Handler(cookieOptions ...context.CookieOption) context.Handler {
return func(ctx context.Context) {
session := s.Start(ctx, cookieOptions...)
ctx.Values().Set(contextSessionKey, session)
ctx.Next()
}
}
// Get returns a *Session from the same request life cycle,
// can be used inside a chain of handlers of a route.
//
// The `Sessions.Start` should be called previously,
// e.g. register the `Sessions.Handler` as middleware.
// Then call `Get` package-level function as many times as you want.
// The `Sessions.Start` can be called more than one time in the same request life cycle as well.
func Get(ctx context.Context) *Session {
if v := ctx.Values().Get(contextSessionKey); v != nil {
if sess, ok := v.(*Session); ok {
return sess
}
}
return nil
}
// StartWithPath same as `Start` but it explicitly accepts the cookie path option.