-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapi.go
112 lines (97 loc) · 1.83 KB
/
api.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package main
import "encoding/json"
type Request struct {
Type string `json:"type"`
Data *Data `json:"data"`
}
type Response struct {
Type string `json:"type"`
Data *Data `json:"data"`
}
func ParseRequest(message string) (*Request, error) {
request := Request{}
err := json.Unmarshal([]byte(message), &request)
if err != nil {
return nil, err
}
return &request, nil
}
type Data struct {
Name string `json:"name"`
Avatar string `json:"avatar"`
Visitor bool `json:"visitor"`
Content string `json:"content"`
Position Position `json:"position"`
OnlineUser []*User `json:"onlineUser"`
}
type Position struct {
X int `json:"x"`
Y int `json:"y"`
}
func CreateResponse(tp string, data *Data) string {
response := Response{
Type: tp,
Data: data,
}
bytes, _ := json.Marshal(&response)
return string(bytes)
}
func HelloMessage(newUser *User) string {
return CreateResponse(
HelloType,
&Data{
Name: newUser.Name,
},
)
}
func MoveMessage(user *User, data *Data) string {
return CreateResponse(
MoveType,
data,
)
}
func TalkMessage(user *User, data *Data) string {
return CreateResponse(
TalkType,
data,
)
}
func EnterMessage(user *User) string {
return CreateResponse(
EnterType,
&Data{
Name: user.Name,
Avatar: user.Avatar,
Position: Position{
X: user.Position.X,
Y: user.Position.Y,
},
Visitor: user.Visitor,
},
)
}
func StandUpMessage(user *User, onlineUserList []*User) string {
return CreateResponse(
StandUpType,
&Data{
OnlineUser: onlineUserList,
},
)
}
func LeaveMessage(user *User) string {
return CreateResponse(
LeaveType,
&Data{
Name: user.Name,
},
)
}
const (
HelloType = "hello"
EnterType = "enter"
MoveType = "move"
RenameType = "rename"
StandUpType = "stand up"
LeaveType = "leave"
TalkType = "talk"
)