@@ 1,8 1,7 @@
package messages
import (
- "encoding/gob"
- "sync"
+ "encoding/json"
"github.com/labstack/echo/v4"
"netlandish.com/x/gobwebs/server"
@@ 23,45 22,31 @@ const (
)
// UserSessionKey session key to store User object
-var UserSessionKey string = "gobwebs.UserSession"
+var UserSessionKey = "gobwebs.UserSession"
// WebMessage is a message to display to a user
type WebMessage struct {
- Level int // 1 debug, 2 info, 3 success, 4 warn, 5 error
- Message string
+ Level int `json:"level"` // 1 debug, 2 info, 3 success, 4 warn, 5 error
+ Message string `json:"message"`
}
// WebMessageStore is the wrapper for messages
type WebMessageStore struct {
- lock sync.Mutex
- Messages []*WebMessage
-}
-
-func init() {
- gob.Register(WebMessage{})
- gob.Register(WebMessageStore{})
+ Messages []*WebMessage `json:"messages"`
}
// Clear clears out all messages
func (w *WebMessageStore) Clear(lock bool) {
- if !lock {
- w.lock.Lock()
- defer w.lock.Unlock()
- }
w.Messages = []*WebMessage{}
}
// Add adds a message
func (w *WebMessageStore) Add(m *WebMessage) {
- w.lock.Lock()
- defer w.lock.Unlock()
w.Messages = append(w.Messages, m)
}
// GetAll returns all messages, clears messages after
func (w *WebMessageStore) GetAll() []*WebMessage {
- w.lock.Lock()
- defer w.lock.Unlock()
msgs := make([]*WebMessage, len(w.Messages))
copy(msgs, w.Messages)
w.Clear(true)
@@ 71,17 56,29 @@ func (w *WebMessageStore) GetAll() []*WebMessage {
// LoadStore loads the session message store
func LoadStore(c echo.Context) *WebMessageStore {
ctx := c.(*server.Context)
- ms, ok := ctx.Server.Session.Get(ctx.Request().Context(), UserSessionKey).(WebMessageStore)
- if !ok {
+ data := ctx.Server.Session.GetBytes(ctx.Request().Context(), UserSessionKey)
+ if data == nil {
+ return &WebMessageStore{}
+ }
+
+ var ms WebMessageStore
+ if err := json.Unmarshal(data, &ms); err != nil {
+ // XXX Log errors
return &WebMessageStore{}
}
+
return &ms
}
// SaveStore saves messages store in session
func SaveStore(c echo.Context, ms *WebMessageStore) {
ctx := c.(*server.Context)
- ctx.Server.Session.Put(ctx.Request().Context(), UserSessionKey, ms)
+ data, err := json.Marshal(ms)
+ if err != nil {
+ // XXX Need logging or error returning
+ return
+ }
+ ctx.Server.Session.Put(ctx.Request().Context(), UserSessionKey, data)
}
// Add adds a message to the messate store