-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
57 lines (53 loc) · 1.43 KB
/
server.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
package main
import (
"encoding/json"
"fmt"
"github.com/googollee/go-socket.io"
"log"
"net/http"
)
func main() {
server, err := socketio.NewServer(nil)
if err != nil {
log.Fatal(err)
}
server.On("connection", func(so socketio.Socket) {
log.Println("on connection")
so.Join("chat")
so.On("chat message", func(msg string) {
log.Println("emit:", so.Emit("chat message", msg))
so.BroadcastTo("chat", "chat message", msg)
})
so.On("disconnection", func() {
log.Println("on disconnect")
})
// 创建case事件
so.On("create_case", func(data string) {
var stb interface{}
err = json.Unmarshal([]byte(data), &stb)
if err != nil {
fmt.Println("create case: 解析json失败")
} else {
obj := stb.(map[string]interface{})
fmt.Println("create case: ", obj["id"])
}
})
})
server.On("create_case", func() {
log.Println("create case")
})
server.On("error", func(so socketio.Socket, err error) {
log.Println("error:", err)
})
//http.Handle("/socket.io/", server)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
log.Println("origin", origin)
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Credentials", "true")
server.ServeHTTP(w, r)
})
//http.Handle("/", http.FileServer(http.Dir("./asset")))
log.Println("Serving at localhost:5000...")
log.Fatal(http.ListenAndServe(":5000", nil))
}