nws/protocol/message.go

79 lines
1.9 KiB
Go
Raw Normal View History

2024-07-22 21:00:21 +00:00
package protocol
import (
"encoding/json"
2024-09-01 19:51:00 +00:00
"fmt"
2024-11-17 21:02:50 +00:00
"github.com/google/uuid"
2024-07-22 21:00:21 +00:00
)
type MessageType string
2024-09-01 19:51:00 +00:00
const (
MessageTypeSocks5 = MessageType("SOCKS5RESPONSE")
MessageConnect = MessageType("CONNECT")
MessageConnectReverse = MessageType("CONNECTR")
2024-07-22 21:00:21 +00:00
)
type Message struct {
2024-11-17 21:02:50 +00:00
Key uuid.UUID `json:"key,omitempty"` // unique identifier for the message
Type MessageType `json:"type,omitempty"` // type of message
Data []byte `json:"data,omitempty"` // data to be sent
Destination string `json:"destination,omitempty"` // destination to send the message
EntryPublicAddress string `json:"entryPublicAddress,omitempty"` // public ip address of the entry node (used for reverse connect)
2024-07-22 21:00:21 +00:00
}
type MessageOption func(*Message)
func WithUUID(uuid uuid.UUID) MessageOption {
return func(m *Message) {
m.Key = uuid
}
}
func WithType(messageType MessageType) MessageOption {
return func(m *Message) {
m.Type = messageType
}
}
2024-07-22 21:00:21 +00:00
func WithDestination(destination string) MessageOption {
return func(m *Message) {
m.Destination = destination
}
}
func WithEntryPublicAddress(entryPublicAddress string) MessageOption {
return func(m *Message) {
m.EntryPublicAddress = entryPublicAddress
}
}
2024-07-22 21:00:21 +00:00
func WithData(data []byte) MessageOption {
return func(m *Message) {
m.Data = data
}
}
func NewMessage(configs ...MessageOption) *Message {
m := &Message{}
for _, config := range configs {
config(m)
}
return m
}
func MarshalJSON(m *Message) ([]byte, error) {
2024-09-01 19:51:00 +00:00
data, err := json.Marshal(m)
if err != nil {
return nil, fmt.Errorf("could not marshal message: %w", err)
}
return data, nil
2024-07-22 21:00:21 +00:00
}
func UnmarshalJSON(data []byte) (*Message, error) {
m := NewMessage()
if err := json.Unmarshal(data, &m); err != nil {
2024-09-01 19:51:00 +00:00
return nil, fmt.Errorf("could not unmarshal message: %w", err)
2024-07-22 21:00:21 +00:00
}
return m, nil
}