-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
103 lines (88 loc) · 1.93 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 (
"fmt"
"github.com/gorilla/websocket"
"net/http"
"github.com/mitchellh/mapstructure"
"time"
)
type Message struct {
Name string `json:"name"`
Data interface{} `json:"data"`
}
type Speaker interface {
Speak()
}
type Channel struct {
Id string `json:"id"`
Name string `json:"name"`
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool{
return true
},
}
func main(){
http.HandleFunc("/", handler)
http.ListenAndServe(":9090", nil)
}
func handler(w http.ResponseWriter, r *http.Request){
//fmt.Fprintf(w, "Hello World from Go!")
socket, err := upgrader.Upgrade(w, r, nil)
if err != nil{
fmt.Println(err)
return
}
for {
var inMessage Message
var outMessage Message
err := socket.ReadJSON(&inMessage)
if err != nil{
fmt.Println(err)
break
}
fmt.Printf("%#v\n", inMessage)
switch inMessage.Name {
case "channel add":
err := addChannel(inMessage.Data)
if err != nil{
outMessage = Message{"error", err} //????
err := socket.WriteJSON(outMessage)
if err != nil{
fmt.Println(err)
break
}
}
//TODO call database function
// if you want to format the output, you can use the keyword 'fallthrough' (uncomment the line below)
// fallthrough
case "channel subscribe":
subscribeChannel(socket)
//TODO call database function
}
}
}
func addChannel(data interface{}) (error) {
fmt.Println("Add Channel Function")
fmt.Println(data)
var channel Channel
err := mapstructure.Decode(data, &channel)
if err != nil{
return err
}
channel.Id = "1"
fmt.Printf("%#v\n", channel)
fmt.Println("Added Channel.")
return nil
}
func subscribeChannel(socket *websocket.Conn){
//TODO call database function (changefeed)
for {
time.Sleep(time.Second * 1)
message := Message{"channel add", Channel{"1", "Software Support"}}
socket.WriteJSON(message)
fmt.Println("sent new channel")
}
}