github.com/mayra-cabrera/buffalo@v0.9.4-0.20170814145312-66d2e7772f11/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  	session, _ := a.SessionStore.Get(r, a.SessionName)
    57  	return &Session{
    58  		Session: session,
    59  		req:     r,
    60  		res:     w,
    61  	}
    62  }