Skip to content

Commit

Permalink
use once
Browse files Browse the repository at this point in the history
  • Loading branch information
LyricTian committed May 9, 2018
1 parent 323ae2d commit 9e14e7e
Showing 1 changed file with 13 additions and 12 deletions.
25 changes: 13 additions & 12 deletions session.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,29 @@ package gearsession

import (
"context"
"sync"

"github.com/teambition/gear"
"gopkg.in/session.v2"
)

// Specify global session manager
var globalManager *session.Manager
var once sync.Once
var internalManager *session.Manager

// Specify the context key
type sessionKey struct{}

func manager(opt ...session.Option) *session.Manager {
once.Do(func() {
internalManager = session.NewManager(opt...)
})
return internalManager
}

// New Create a session middleware
func New(opt ...session.Option) gear.Middleware {
globalManager = session.NewManager(opt...)
return func(ctx *gear.Context) error {
store, err := globalManager.Start(context.Background(), ctx.Res, ctx.Req)
store, err := manager(opt...).Start(context.Background(), ctx.Res, ctx.Req)
if err != nil {
return err
}
Expand All @@ -34,16 +41,10 @@ func FromContext(ctx *gear.Context) session.Store {

// Destroy Destroy a session
func Destroy(ctx *gear.Context) error {
if globalManager == nil {
return nil
}
return globalManager.Destroy(context.Background(), ctx.Res, ctx.Req)
return manager().Destroy(context.Background(), ctx.Res, ctx.Req)
}

// Refresh a session and return to session storage
func Refresh(ctx *gear.Context) (session.Store, error) {
if globalManager == nil {
return nil, nil
}
return globalManager.Refresh(context.Background(), ctx.Res, ctx.Req)
return manager().Refresh(context.Background(), ctx.Res, ctx.Req)
}

0 comments on commit 9e14e7e

Please sign in to comment.