ribbit/page_session.go

59 lines
1.3 KiB
Go
Raw Permalink Normal View History

2018-04-26 11:53:03 +00:00
package main
import (
2019-01-10 16:39:42 +00:00
"errors"
2018-04-26 11:53:03 +00:00
"fmt"
"net/http"
"github.com/gorilla/sessions"
)
// This is basically a convenience struct for
// easier session management (hopefully ;)
type pageSession struct {
session *sessions.Session
req *http.Request
w http.ResponseWriter
}
func (p *pageSession) getStringValue(key string) (string, error) {
2019-01-10 16:39:42 +00:00
if p.session == nil {
return "", errors.New("Session is nil")
}
2018-04-26 11:53:03 +00:00
val := p.session.Values[key]
var retVal string
var ok bool
if retVal, ok = val.(string); !ok {
return "", fmt.Errorf("Unable to create string from %s", key)
}
return retVal, nil
}
func (p *pageSession) setStringValue(key, val string) {
p.session.Values[key] = val
p.session.Save(p.req, p.w)
}
func (p *pageSession) setFlashMessage(msg, status string) {
p.setStringValue("flash_message", msg)
p.setStringValue("flash_status", status)
}
func (p *pageSession) getFlashMessage() (string, string) {
var err error
var msg, status string
if msg, err = p.getStringValue("flash_message"); err != nil {
return "", "hidden"
}
if status, err = p.getStringValue("flash_status"); err != nil {
return "", "hidden"
}
p.setFlashMessage("", "hidden")
return msg, status
}
func (p *pageSession) expireSession() {
p.session.Options.MaxAge = -1
p.session.Save(p.req, p.w)
}