forked from trevex/golem_examples
/
example_connection_extension.go
91 lines (77 loc) · 2.32 KB
/
example_connection_extension.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
package main
import (
"flag"
"fmt"
"github.com/trevex/golem"
"log"
"net/http"
)
var addr = flag.String("addr", ":8080", "http service address")
// This struct represents the message which is accepted by
// the hello-function.
// If a handler function takes a special data
// type that is not an byte array, golem automatically
// tries to unmarshal the data into the specific type.
type Hello struct {
To string `json:"to"`
From string `json:"from"`
}
// Type of data being emitted with answer-Event
type Answer struct {
Msg string `json:"msg"`
}
// Extended connection type embedding the simple connection to provide the same functionality.
type ExtendedConnection struct {
*golem.Connection
Counter int
}
// An additional method for the extended type
func (e *ExtendedConnection) answer(msg string) {
e.Emit("answer", &Answer{msg})
}
// Constructor of the extended connection
func NewExtendedConnection(conn *golem.Connection) *ExtendedConnection {
return &ExtendedConnection{
Connection: conn,
Counter: 1, // to illustrate the persistence of the extension
}
}
// Function taken special data type and utilizing golem's
// inbuilt unmarshalling
func hello(conn *ExtendedConnection, data *Hello) {
conn.Counter += 1
fmt.Println("Hello from", data.From, "to", data.To, "Counter:", conn.Counter)
conn.answer("Thanks, client!")
}
// Event but no data transmission
func poke(conn *ExtendedConnection) {
conn.Counter += 1
fmt.Println("Poke-Event triggered! Counter:", conn.Counter)
conn.answer("Ouch I am sensible!")
}
func main() {
flag.Parse()
// Create a router
myrouter := golem.NewRouter()
// Enable the extension
myrouter.SetConnectionExtension(NewExtendedConnection)
// Add the events to the router
myrouter.On("hello", hello)
myrouter.On("poke", poke)
// Close callback
myrouter.OnClose(func(conn *ExtendedConnection) {
fmt.Println("Connection closed with counter at:", conn.Counter)
})
// Connect callback
myrouter.OnConnect(func(conn *ExtendedConnection) {
fmt.Println("User connected counter at:", conn.Counter)
})
// 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)
}
}