-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
103 lines (86 loc) · 2.27 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
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/gorilla/websocket"
"log"
"net/http"
"strings"
)
var chttp *http.ServeMux
func main() {
fmt.Println("Hello World !")
chttp = http.NewServeMux()
chttp.Handle("/", http.FileServer(http.Dir("./")))
http.HandleFunc("/", HomeHandler)
http.ListenAndServe(":8080", nil)
}
func HomeHandler(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, ".") {
chttp.ServeHTTP(w, r)
} else {
http.Error(w, "Not found", 404)
}
}
type chatMsg struct {
Level string `json:"level,omitempty"`
Msg string `json:"msg,omitempty"`
Ttl int64 `json:"ttl,omitempty"`
Namespace string `json:"namespace,omitempty"`
Read bool `json:"read"`
Seen bool `json:"seen"`
}
type ChatSocket struct {
upgrader *websocket.Upgrader
}
func NewChatSocket() *ChatSocket {
var chatSocket = &ChatSocket{
upgrader: &websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { return true },
},
}
return chatSocket
}
func (cs *ChatSocket) ServeHTTP(w http.ResponseWriter, r *http.Request) {
conn, err := cs.upgrader.Upgrade(w, r, nil)
defer conn.Close()
if _, ok := err.(websocket.HandshakeError); ok {
wsHandleError(cs, w, conn, fmt.Errorf("Not a websocket handshake"))
return
} else if err != nil {
wsHandleError(cs, w, conn, fmt.Errorf("Connection error"))
return
}
pingBytes := 0
for {
msgType, msg, err := conn.ReadMessage()
if err != nil {
wsHandleError(cs, w, conn, fmt.Errorf("Unreadable message"))
return
}
if msgType == websocket.TextMessage {
d := json.NewDecoder(bytes.NewReader(msg))
var msg chatMsg
if decodeErr := d.Decode(&msg); decodeErr != nil {
wsHandleError(cs, w, conn, fmt.Errorf("Unreadable JSON message %s", decodeErr.Error()))
return
}
log.Println("Socket Received message", string(msg))
var b bytes.Buffer
encoder := json.NewEncoder(&b)
encodeErr := encoder.Encode(msg)
if err == nil {
conn.WriteMessage(websocket.TextMessage, b)
}
} else {
pingBytes += len(msg)
}
}
}
func wsHandleError(cs *ChatSocket, w http.ResponseWriter, conn *websocket.Conn, err error) {
http.Error(w, err.Error(), 400)
log.Println("Websocket connection error : ", err)
}