github.com/segakazzz/buffalo@v0.16.22-0.20210119082501-1f52048d3feb/session.go (about)

     1  package buffalo
     2  
     3  import (
     4  	"net/http"
     5  
     6  	"github.com/gorilla/sessions"
     7  )
     8  
     9  // Session wraps the "github.com/gorilla/sessions" API
    10  // in something a little cleaner and a bit more useable.
    11  type Session struct {
    12  	Session *sessions.Session
    13  	req     *http.Request
    14  	res     http.ResponseWriter
    15  }
    16  
    17  // Save the current session.
    18  func (s *Session) Save() error {
    19  	return s.Session.Save(s.req, s.res)
    20  }
    21  
    22  // Get a value from the current session.
    23  func (s *Session) Get(name interface{}) interface{} {
    24  	return s.Session.Values[name]
    25  }
    26  
    27  // GetOnce gets a value from the current session and then deletes it.
    28  func (s *Session) GetOnce(name interface{}) interface{} {
    29  	if x, ok := s.Session.Values[name]; ok {
    30  		s.Delete(name)
    31  		return x
    32  	}
    33  	return nil
    34  }
    35  
    36  // Set a value onto the current session. If a value with that name
    37  // already exists it will be overridden with the new value.
    38  func (s *Session) Set(name, value interface{}) {
    39  	s.Session.Values[name] = value
    40  }
    41  
    42  // Delete a value from the current session.
    43  func (s *Session) Delete(name interface{}) {
    44  	delete(s.Session.Values, name)
    45  }
    46  
    47  // Clear the current session
    48  func (s *Session) Clear() {
    49  	for k := range s.Session.Values {
    50  		s.Delete(k)
    51  	}
    52  }
    53  
    54  // Get a session using a request and response.
    55  func (a *App) getSession(r *http.Request, w http.ResponseWriter) *Session {
    56  	if a.root != nil {
    57  		return a.root.getSession(r, w)
    58  	}
    59  	session, _ := a.SessionStore.Get(r, a.SessionName)
    60  	return &Session{
    61  		Session: session,
    62  		req:     r,
    63  		res:     w,
    64  	}
    65  }
    66  
    67  func sessionSaver(next Handler) Handler {
    68  	return func(c Context) error {
    69  		err := next(c)
    70  		if err != nil {
    71  			return err
    72  		}
    73  		return c.Session().Save()
    74  	}
    75  }