-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmessage.go
85 lines (70 loc) · 1.46 KB
/
message.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"encoding/json"
"fmt"
)
type MessageType int
const (
UnknownMessageType MessageType = iota
ErrorMessageType
ChatMessageType
NickMessageType
)
func (t MessageType) String() string {
switch t {
case ChatMessageType:
return "ChatMessage"
case NickMessageType:
return "NickMessage"
case ErrorMessageType:
return "ErrorMessage"
default:
return fmt.Sprintf("UnsupportedMessage(%d)", int(t))
}
}
func (t MessageType) MarshalJSON() ([]byte, error) {
return []byte("\"" + t.String() + "\""), nil
}
func (t *MessageType) UnmarshalJSON(bs []byte) error {
mt := string(bs)
if mt == "\"ChatMessage\"" {
*t = ChatMessageType
} else if mt == "\"NickMessage\"" {
*t = NickMessageType
} else {
*t = UnknownMessageType
}
return nil
}
type Message interface {
Type() MessageType
}
type Frame struct {
Type MessageType `json:"type"`
Data json.RawMessage `json:"data"`
}
const (
ErrInvalidNick = "InvalidNick"
ErrNoNickSet = "NoNickSet"
)
type ErrorMessage struct {
ErrorCode string `json:"error_code"`
Message string `json:"message"`
}
func (m *ErrorMessage) Type() MessageType {
return ErrorMessageType
}
type ChatMessage struct {
Author string `json:"author"`
Body string `json:"body"`
}
func (m *ChatMessage) Type() MessageType {
return ChatMessageType
}
type NickMessage struct {
OldName string `json:"old_name"`
NewName string `json:"new_name"`
}
func (m *NickMessage) Type() MessageType {
return NickMessageType
}