2021-12-03 03:11:01 -08:00
|
|
|
package msg
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/gorilla/sessions"
|
|
|
|
"github.com/labstack/echo-contrib/session"
|
|
|
|
"github.com/labstack/echo/v4"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Type string
|
|
|
|
|
|
|
|
const (
|
2021-12-03 13:44:04 -08:00
|
|
|
TypeSuccess Type = "success"
|
|
|
|
TypeInfo Type = "info"
|
|
|
|
TypeWarning Type = "warning"
|
|
|
|
TypeDanger Type = "danger"
|
2021-12-03 03:11:01 -08:00
|
|
|
)
|
|
|
|
|
2021-12-03 13:44:04 -08:00
|
|
|
// TODO: Error handling and cleanup
|
2021-12-03 03:11:01 -08:00
|
|
|
|
2021-12-03 13:44:04 -08:00
|
|
|
func Success(c echo.Context, message string) {
|
|
|
|
Set(c, TypeSuccess, message)
|
|
|
|
}
|
|
|
|
|
|
|
|
func Info(c echo.Context, message string) {
|
|
|
|
Set(c, TypeInfo, message)
|
|
|
|
}
|
|
|
|
|
|
|
|
func Warning(c echo.Context, message string) {
|
|
|
|
Set(c, TypeWarning, message)
|
|
|
|
}
|
|
|
|
|
|
|
|
func Danger(c echo.Context, message string) {
|
|
|
|
Set(c, TypeDanger, message)
|
2021-12-03 03:11:01 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Set adds a new message into the cookie storage.
|
2021-12-03 13:44:04 -08:00
|
|
|
func Set(c echo.Context, typ Type, message string) {
|
2021-12-03 03:11:01 -08:00
|
|
|
sess := getSession(c)
|
2021-12-03 13:44:04 -08:00
|
|
|
sess.AddFlash(message, string(typ))
|
2021-12-03 03:11:01 -08:00
|
|
|
_ = sess.Save(c.Request(), c.Response())
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get gets flash messages from the cookie storage.
|
|
|
|
func Get(c echo.Context, typ Type) []string {
|
|
|
|
sess := getSession(c)
|
|
|
|
fm := sess.Flashes(string(typ))
|
|
|
|
// If we have some messages.
|
|
|
|
if len(fm) > 0 {
|
|
|
|
_ = sess.Save(c.Request(), c.Response())
|
|
|
|
// Initiate a strings slice to return messages.
|
|
|
|
var flashes []string
|
|
|
|
for _, fl := range fm {
|
|
|
|
// Add message to the slice.
|
|
|
|
flashes = append(flashes, fl.(string))
|
|
|
|
}
|
|
|
|
|
|
|
|
return flashes
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2021-12-03 13:44:04 -08:00
|
|
|
|
|
|
|
func getSession(c echo.Context) *sessions.Session {
|
|
|
|
sess, _ := session.Get("msg", c)
|
|
|
|
return sess
|
|
|
|
}
|