This repository has been archived by the owner on Nov 28, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
272 lines (216 loc) · 6.29 KB
/
main.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"strconv"
"strings"
"time"
"github.com/DeanThompson/ginpprof"
"github.com/elsonwu/goio"
"github.com/gin-gonic/gin"
"github.com/golang/glog"
)
var flagHost = flag.String("host", "127.0.0.1:9999", "the default server host")
var flagSSLHost = flag.String("sslhost", "", "the server host for https, it will override the host setting")
var flagAllowOrigin = flag.String("alloworigin", "*", "the host allow to cross site ajax")
var flagDebug = flag.Bool("debug", false, "enable debug mode or not")
var flagGCPeriod = flag.Int("gcperiod", 5, "how many seconds to run gc")
var flagClientLifeCycle = flag.Int64("lifecycle", 30, "how many seconds of the client life cycle")
var flagClientMessageTimeout = flag.Int("messagetimeout", 15, "how many seconds of the client keep waiting for new messages")
var flagEnableHttps = flag.Bool("enablehttps", false, "enable https or not")
var flagDisableHttp = flag.Bool("disablehttp", false, "disable http and use https only")
var flagCertFile = flag.String("certfile", "", "certificate file path")
var flagKeyFile = flag.String("keyfile", "", "private file path")
func main() {
flag.Parse()
goio.GCPeriod = *flagGCPeriod
goio.LifeCycle = *flagClientLifeCycle
goio.Run()
m := gin.New()
m.Use(gin.Recovery())
if *flagDebug {
m.Use(gin.Logger())
} else {
gin.SetMode(gin.ReleaseMode)
}
m.Use(func(ctx *gin.Context) {
ctx.Header("Content-Type", "text/plain; charset=utf-8")
ctx.Header("Access-Control-Allow-Credentials", "true")
ctx.Header("Access-Control-Allow-Methods", "GET,POST")
ctx.Header("Powered-By", "Goio")
if "" != *flagAllowOrigin {
allowOrigins := strings.Split(*flagAllowOrigin, ",")
for _, allowOrigin := range allowOrigins {
ctx.Writer.Header().Add("Access-Control-Allow-Origin", allowOrigin)
}
}
})
m.Use(func(ctx *gin.Context) {
ctx.Next()
ctx.Request.Close = true
ctx.Request.Body.Close()
})
m.GET("/count", func(ctx *gin.Context) {
s := fmt.Sprintf("rooms: %d, users: %d, clients: %d \n", goio.Rooms().Count(), goio.Users().Count(), goio.Clients().Count())
if yes, _ := ctx.GetQuery("debug"); yes == "1" {
s = s + "#Rooms\n"
goio.Rooms().Range(func(r *goio.Room) {
s = s + " - " + r.Id + " user count:" + strconv.Itoa(r.UserCount()) + "\n"
})
s = s + "\n"
s = s + "#Users\n"
goio.Users().Range(func(u *goio.User) {
s = s + " - " + u.Id + " client count:" + strconv.Itoa(u.ClientCount()) + "\n"
})
s = s + "\n"
s = s + "#Clients\n"
goio.Clients().Range(func(c *goio.Client) {
s = s + " - " + c.Id + " user ID:" + c.User.Id + " user client count:" + strconv.Itoa(c.User.ClientCount()) + "\n"
})
}
ctx.String(200, s)
})
// get user ids array from the given room
m.GET("/room/users/:room_id", func(ctx *gin.Context) {
roomId := ctx.Param("room_id")
room := goio.Rooms().Get(roomId)
if room == nil {
ctx.String(200, "")
return
}
ctx.String(200, strings.Join(room.UserIds(), ","))
})
m.GET("/user/data/:user_id/:key", func(ctx *gin.Context) {
userId := ctx.Param("user_id")
key := ctx.Param("key")
user := goio.Users().Get(userId)
if user == nil {
ctx.String(200, "")
return
}
ctx.String(200, user.GetData(key))
})
m.POST("/user/data/:client_id/:key", func(ctx *gin.Context) {
val, err := ioutil.ReadAll(ctx.Request.Body)
ctx.Request.Body.Close()
if err != nil {
ctx.String(500, err.Error())
return
}
clientId := ctx.Param("client_id")
key := ctx.Param("key")
clt := goio.Clients().Get(clientId)
if clt != nil && clt.User != nil {
clt.User.AddData(key, string(val))
}
ctx.String(204, "")
})
m.POST("/online_status", func(ctx *gin.Context) {
val, err := ioutil.ReadAll(ctx.Request.Body)
ctx.Request.Body.Close()
if err != nil {
glog.V(1).Infof("online_status error %s\n", err.Error())
ctx.String(500, err.Error())
return
}
userIds := strings.Split(string(val), ",")
glog.V(1).Infof("checking userIds:%s\n", string(val))
status := ""
for _, userId := range userIds {
if nil == goio.Users().Get(userId) {
status += "0,"
} else {
status += "1,"
}
}
ctx.String(200, status)
})
m.POST("/client/:user_id", func(ctx *gin.Context) {
userId := ctx.Param("user_id")
user := goio.Users().MustGet(userId)
clt := goio.NewClient(user)
ctx.String(200, clt.Id)
})
m.GET("/kill_client/:client_id", func(ctx *gin.Context) {
clt := goio.Clients().Get(ctx.Param("client_id"))
if clt != nil {
clt.SetIsDead()
}
ctx.String(204, "")
})
m.GET("/message/:client_id", func(ctx *gin.Context) {
id := ctx.Param("client_id")
clt := goio.Clients().Get(id)
if clt == nil || clt.IsDead() {
ctx.String(404, fmt.Sprintf("Client %s does not exist\n", id))
return
}
for i := 0; i <= *flagClientMessageTimeout; i++ {
msgs := clt.ReadMessages()
if len(msgs) == 0 {
<-time.After(time.Second)
continue
}
m, err := json.Marshal(msgs)
if err != nil {
ctx.String(500, err.Error())
return
}
ctx.String(200, string(m))
return
}
ctx.String(200, "")
})
m.POST("/message/:client_id", func(ctx *gin.Context) {
id := ctx.Param("client_id")
clt := goio.Clients().Get(id)
if clt == nil || clt.IsDead() {
ctx.String(403, fmt.Sprintf("Client %s does not exist\n", id))
return
}
if clt.User == nil {
ctx.String(403, fmt.Sprintf("Client %s does not connect with any user\n", id))
return
}
msg := &goio.Message{}
ctx.BindJSON(msg)
msg.CallerId = clt.User.Id
msg.ClientId = clt.Id
goio.SendMessage(msg, clt)
ctx.String(204, "")
})
m.OPTIONS("/*path", func(ctx *gin.Context) {})
// Register pprof handlers
ginpprof.Wrap(m)
host := *flagHost
if !*flagEnableHttps && *flagDisableHttp {
glog.Errorln("You cannot disable http but not enable https in the same time")
return
}
//Prevent exiting
ch := make(chan bool)
if !*flagDisableHttp {
go func() {
log.Println("Serve at " + host + " - http")
if err := http.ListenAndServe(host, m); err != nil {
log.Println(err)
}
}()
}
if *flagEnableHttps {
go func() {
if *flagSSLHost != "" {
host = *flagSSLHost
}
log.Println("Serve at " + host + " - https")
if err := http.ListenAndServeTLS(host, *flagCertFile, *flagKeyFile, m); err != nil {
log.Println(err)
}
}()
}
<-ch
}