croc/src/message/message.go

61 lines
1.2 KiB
Go
Raw Normal View History

2019-04-30 02:03:19 +02:00
package message
import (
"encoding/json"
2019-04-30 04:50:01 +02:00
"github.com/schollz/croc/v6/src/comm"
2019-04-30 02:03:19 +02:00
"github.com/schollz/croc/v6/src/compress"
"github.com/schollz/croc/v6/src/crypt"
2019-09-07 18:41:24 +02:00
log "github.com/schollz/logger"
2019-04-30 02:03:19 +02:00
)
2019-04-30 04:19:48 +02:00
// Message is the possible payload for messaging
2019-04-30 02:03:19 +02:00
type Message struct {
Type string `json:"t,omitempty"`
Message string `json:"m,omitempty"`
Bytes []byte `json:"b,omitempty"`
Num int `json:"n,omitempty"`
}
2019-04-30 04:19:48 +02:00
func (m Message) String() string {
b, _ := json.Marshal(m)
return string(b)
}
2019-04-30 04:50:01 +02:00
// Send will send out
2019-11-18 16:53:57 +01:00
func Send(c *comm.Comm, key []byte, m Message) (err error) {
2020-02-28 21:58:46 +01:00
log.Debugf("writing %s message", m.Type)
2019-04-30 04:50:01 +02:00
mSend, err := Encode(key, m)
2019-04-30 04:19:48 +02:00
if err != nil {
return
}
_, err = c.Write(mSend)
2019-04-30 04:50:01 +02:00
return
2019-04-30 04:19:48 +02:00
}
// Encode will convert to bytes
2019-11-18 16:53:57 +01:00
func Encode(key []byte, m Message) (b []byte, err error) {
2019-04-30 02:03:19 +02:00
b, err = json.Marshal(m)
if err != nil {
return
}
b = compress.Compress(b)
2019-11-18 16:53:57 +01:00
if key != nil {
b, err = crypt.Encrypt(b, key)
}
2019-04-30 02:03:19 +02:00
return
}
2019-04-30 04:19:48 +02:00
// Decode will convert from bytes
2019-11-18 16:53:57 +01:00
func Decode(key []byte, b []byte) (m Message, err error) {
if key != nil {
b, err = crypt.Decrypt(b, key)
if err != nil {
return
}
2019-04-30 02:03:19 +02:00
}
b = compress.Decompress(b)
err = json.Unmarshal(b, &m)
return
}