-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathexample_data.go
87 lines (74 loc) · 2.31 KB
/
example_data.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
package main
import (
"flag"
"fmt"
"github.com/trevex/golem"
"log"
"net/http"
)
var addr = flag.String("addr", ":8080", "http service address")
// This struct represent the message the json function
// should receive. If a function takes a special data
// type that is not an byte array, golem automatically
// tries to unmarshal the data in to this specific type.
// Since the json package is used tags work as well.
type ChatMessage struct {
Msg string `json:"msg"`
}
// Function taken special data type and utilizing golem's
// inbuilt unmarshalling
func json(conn *golem.Connection, data *ChatMessage) {
fmt.Println("JSON: ", data.Msg)
conn.Emit("json", &data)
}
// If a function accepts a byte array the data is directly
// forwarded to the function without any parsing involved.
// Hence it is the fastest way.
func raw(conn *golem.Connection, data interface{}) {
fmt.Println("Raw: ", string(data.([]byte)))
conn.Emit("raw", []byte("Raw byte array received."))
}
// Event but no data transmission
func nodata(conn *golem.Connection) {
fmt.Println("Nodata: Event triggered.")
conn.Emit("json", &ChatMessage{"Hi from nodata!"})
}
// If a parser is known for the specific data type it is
// automatically used.
func custom(conn *golem.Connection, data string) {
fmt.Println("Custom:", data)
conn.Emit("custom", "Custom handler use to receive data.")
}
// Custom parsers take a byte array as argument and return
// the data type they parse to and a boolean (to validate if
// parsing was successful).
func stringExtension(data interface{}) (string, bool) {
return string(data.([]byte)), true
}
func main() {
flag.Parse()
// Create a router
myrouter := golem.NewRouter()
// Add the custom parser that returns strings
err := myrouter.AddProtocolExtension(stringExtension)
if err != nil {
fmt.Println(err)
}
// Add the events to the router
myrouter.On("json", json)
myrouter.On("raw", raw)
myrouter.On("custom", custom)
myrouter.On("nodata", nodata)
//
myrouter.OnClose(func(conn *golem.Connection) {
fmt.Println("Client disconnected!")
})
// Serve the public files
http.Handle("/", http.FileServer(http.Dir("./public")))
// Handle websockets using golems handler
http.HandleFunc("/ws", myrouter.Handler())
// Listen
if err := http.ListenAndServe(*addr, nil); err != nil {
log.Fatal("ListenAndServe:", err)
}
}