-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebrosie.go
106 lines (87 loc) · 2.24 KB
/
webrosie.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
104
105
106
package main
//go:generate go-bindata -nomemcopy -nometadata -ignore=\.map$ public/...
import (
"context"
"log"
"net/http"
"github.com/elazarl/go-bindata-assetfs"
"github.com/gorilla/websocket"
"github.com/grandcat/zeroconf"
)
type message struct {
Name string `json:"name"`
Host string `json:"host"`
Port int `json:"port"`
}
var (
clients = make(map[*websocket.Conn]bool)
broadcast = make(chan *message)
upgrader = websocket.Upgrader{}
oldmsgs []*message
)
func handleRosieDiscover(results <-chan *zeroconf.ServiceEntry) {
for entry := range results {
log.Println("Found rosie:", entry.Instance, entry.AddrIPv4[0].String(), entry.Port)
msg := new(message)
msg.Name = entry.Instance
msg.Host = entry.AddrIPv4[0].String()
msg.Port = entry.Port
broadcast <- msg
oldmsgs = append(oldmsgs, msg)
}
}
func handleWSConnection(w http.ResponseWriter, r *http.Request) {
// Upgrade GET request to a websocket
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Fatalln("Failed to upgrade:", err)
}
log.Println("Connected client:", ws.RemoteAddr().String())
clients[ws] = true
// send all the clients all the already know hosts
for ws := range clients {
for _, msg := range oldmsgs {
sendMessage(msg, ws)
}
}
}
func sendMessage(msg *message, ws *websocket.Conn) {
if err := ws.WriteJSON(msg); err != nil {
log.Println("Failed to send:", err)
defer ws.Close()
delete(clients, ws)
}
}
func broadcastInfo() {
for {
msg := <-broadcast
for ws := range clients {
sendMessage(msg, ws)
}
}
}
func main() {
resolver, err := zeroconf.NewResolver(nil)
if err != nil {
log.Fatalln("Failed to initialize resolver", err)
}
entries := make(chan *zeroconf.ServiceEntry)
go handleRosieDiscover(entries)
go broadcastInfo()
ctx := context.Background()
if err = resolver.Browse(ctx, "_rosieapi._tcp", "local", entries); err != nil {
log.Fatalln("Failed to browse", err)
}
// serve webrosie page
http.Handle("/",
http.FileServer(&assetfs.AssetFS{
Asset: Asset,
AssetDir: AssetDir,
Prefix: "public"}))
// add websocket route
http.HandleFunc("/ws", handleWSConnection)
if err = http.ListenAndServe(":8080", nil); err != nil {
log.Fatalln("Failed to start HTTP server", err)
}
<-ctx.Done()
}