-
Notifications
You must be signed in to change notification settings - Fork 0
/
web_client_endpoint.go
77 lines (63 loc) · 1.61 KB
/
web_client_endpoint.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
package main
import (
"github.com/gin-gonic/gin"
"gopkg.in/olahol/melody.v1"
"net/http"
)
var clientMelody = melody.New()
func handleClientEndpoint(c *gin.Context) {
ns := c.Query("namespace")
if len(ns) > cnf.Auth.MaxNamespaceLength {
err := c.AbortWithError(400, NamespaceTooLong)
if err != nil {
errorLogger.Println(err)
c.Abort()
return
}
}
err := clientMelody.HandleRequest(c.Writer, c.Request)
if err != nil {
err := c.AbortWithError(400, err)
if err != nil {
errorLogger.Println(err)
c.Abort()
return
}
}
}
func setupMelody() {
clientMelody.HandleError(func(session *melody.Session, err error) {
errorLogger.Println(err)
})
clientMelody.HandleConnect(func(s *melody.Session) {
// build Session
var query = s.Request.URL.Query()
var namespace = query.Get("namespace")
var remoteIp = readUserIp(s.Request)
id, session := NewSession(namespace, remoteIp, s, false)
s.Set("Session", session)
infoLogger.Println("Accepted public client", id)
broadcastClientJoin(session)
})
clientMelody.HandleDisconnect(func(s *melody.Session) {
// get Session
var r, _ = s.Get("Session")
var session = r.(*Session)
infoLogger.Println("Dropping public client", session.Id)
UnmapSession(session.Id, false)
broadcastClientLeave(session)
})
clientMelody.HandleMessage(func(s *melody.Session, msg []byte) {
// TODO: Make this work, somehow
})
}
func readUserIp(r *http.Request) string {
IPAddress := r.Header.Get("X-Real-Ip")
if IPAddress == "" {
IPAddress = r.Header.Get("X-Forwarded-For")
}
if IPAddress == "" {
IPAddress = r.RemoteAddr
}
return IPAddress
}