travebing/backend/notifier/message.go

99 lines
1.8 KiB
Go

package notifier
import (
"encoding/json"
"errors"
"strconv"
)
type MessageType int
const (
MessageTypeOpened MessageType = iota
MessageTypeSystem
)
type Message struct {
Type MessageType `json:"type"`
To string `json:"to"`
Data interface{} `json:"data"`
ID string `json:"id"`
}
func NewMessage(data []byte)(Message, error){
m := Message{}
err := json.Unmarshal(data, &m)
return m, err
}
func NewMessageFromMap(m map[string]interface{})(Message, error){
msg := Message{}
to := m["to"]
typ := m["type"]
data := m["data"]
if t, ok := to.(string); ok {
msg.To = t
}else{
return msg, errors.New("field to type error")
}
if ty, ok := typ.(string); ok {
i, _ := strconv.Atoi(ty)
msg.Type = MessageType(i)
}else{
return msg, errors.New("field type type error")
}
msg.Data = data
return msg, nil
}
func (m Message) IDString() string {
return strconv.Itoa(int(m.Type))
}
func (m Message) SSEIDBytes() []byte {
return []byte("id: " + m.TypeString() + "\n")
}
func (m Message) TypeString() string {
return strconv.Itoa(int(m.Type))
}
func (m Message) SSETypeBytes() []byte {
return []byte("event: " + m.TypeString() + "\n")
}
func (m Message) Bytes() ([]byte, error) {
return json.Marshal(&m)
}
func (m Message) SSEBytes() ([]byte, error) {
data, err := m.Bytes()
if err != nil {
return []byte("data: "), err
}
return []byte("data: " + string(data) + "\n\n"), nil
}
func (m Message) DataBytes() ([]byte, error) {
return json.Marshal(m.Data)
}
func (m Message) SSEDataBytes() ([]byte, error) {
data, err := m.DataBytes()
if err != nil {
return []byte("data: "), err
}
return []byte("data: " + string(data) + "\n\n"), nil
}
func (m Message)Map()map[string]interface{}{
ret := make(map[string]interface{}, 0)
ret["type"] = int(m.Type)
ret["id"] = m.ID
ret["to"] = m.To
ret["data"] = m.Data
return ret
}