sonar/sessions.go

41 lines
1.1 KiB
Go

package sonar
import (
"fmt"
"net/http"
)
// Abort with an error.
func (s *Sonar) Abort(r *http.Request, w http.ResponseWriter, message string, v ...interface{}) {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, message, v...)
}
// FlashAndRedirect to flash and redirect away.
func (s *Sonar) FlashAndRedirect(r *http.Request, w http.ResponseWriter, url string, flash string, v ...interface{}) {
log.Debug("Flash: %s", fmt.Sprintf(flash, v...))
s.Flash(r, w, fmt.Sprintf(flash, v...))
w.Header().Add("Location", url)
w.WriteHeader(http.StatusFound)
}
// Flash a message to the user.
func (s *Sonar) Flash(r *http.Request, w http.ResponseWriter, tmpl string, v ...string) {
session, _ := s.sessions.Get(r, s.Config.CookieName)
session.AddFlash(tmpl, v...)
session.Save(r, w)
}
// GetFlashes retrieves the flashed messages.
func (s *Sonar) GetFlashes(r *http.Request, w http.ResponseWriter) []string {
var result []string
session, _ := s.sessions.Get(r, s.Config.CookieName)
if flashes := session.Flashes(); len(flashes) > 0 {
for _, flash := range flashes {
result = append(result, flash.(string))
}
}
session.Save(r, w)
return result
}