-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmessage.go
81 lines (64 loc) · 1.9 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
package message
import (
"fmt"
"strings"
)
// Command - command type
type Command int8
const (
// CommandError - using when something went wrong by client or server
CommandError Command = iota
// CommandRequestPuzzle - using when client requests puzzle from server
CommandRequestPuzzle
// CommandResponsePuzzle - using when server sends puzzle to client
CommandResponsePuzzle
// CommandRequestResource - using when client requests resource from server
CommandRequestResource
// CommandResponseResource - using when server sends resource to client
CommandResponseResource
)
const (
// DelimiterMessage - sign to devide messages from each other
DelimiterMessage = '\n'
// DelimiterCommand - sign to devide command and payload in message
DelimiterCommand = ':'
)
// ParseMessage - parse message from string
// string has "command:payload" format where command could be 0-4
func ParseMessage(msg string) (m Message, err error) {
msg = strings.TrimSpace(msg)
if len(msg) < 2 {
return m, ErrIncorrectMessageFormat
}
switch msg[:2] {
case fmt.Sprintf("0%c", DelimiterCommand):
m.Command = CommandError
case fmt.Sprintf("1%c", DelimiterCommand):
m.Command = CommandRequestPuzzle
case fmt.Sprintf("2%c", DelimiterCommand):
m.Command = CommandResponsePuzzle
case fmt.Sprintf("3%c", DelimiterCommand):
m.Command = CommandRequestResource
case fmt.Sprintf("4%c", DelimiterCommand):
m.Command = CommandResponseResource
default:
return m, ErrIncorrectMessageFormat
}
if len(msg) > 2 {
m.Payload = strings.TrimSpace(msg[2:])
}
return
}
// Message - message with command and payload
type Message struct {
Command Command
Payload string
}
// String - format message as string
func (m Message) String() string {
return fmt.Sprintf("%d%c%s%c", m.Command, DelimiterCommand, m.Payload, DelimiterMessage)
}
// Bytes - format message as bytes
func (m Message) Bytes() []byte {
return []byte(m.String())
}