/
dispatcher.go
77 lines (64 loc) · 1.79 KB
/
dispatcher.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
package console
import (
"fmt"
"html/template"
"log"
"net/http"
"github.com/elazarl/go-bindata-assetfs"
"github.com/jmartin82/mmock/definition"
"golang.org/x/net/websocket"
)
//Dispatcher is the http console server.
type Dispatcher struct {
IP string
Port int
Mlog chan definition.Match
clients []*websocket.Conn
}
func (di *Dispatcher) consoleHandler(w http.ResponseWriter, r *http.Request) {
tmpl, _ := Asset("tmpl/index.html")
t, _ := template.New("Console").Parse(string(tmpl))
t.Execute(w, &di)
}
func (di *Dispatcher) removeClient(i int) {
copy(di.clients[i:], di.clients[i+1:])
di.clients[len(di.clients)-1] = nil
di.clients = di.clients[:len(di.clients)-1]
}
func (di *Dispatcher) addClient(ws *websocket.Conn) {
di.clients = append(di.clients, ws)
}
func (di *Dispatcher) echoHandler(ws *websocket.Conn) {
defer func() {
ws.Close()
}()
di.addClient(ws)
//block
var message string
websocket.Message.Receive(ws, &message)
}
func (di *Dispatcher) logFanOut() {
for match := range di.Mlog {
for i, c := range di.clients {
if c != nil {
if err := websocket.JSON.Send(c, match); err != nil {
di.removeClient(i)
}
}
}
}
}
//Start initiates the http console.
func (di *Dispatcher) Start() {
di.clients = []*websocket.Conn{}
http.Handle("/echo", websocket.Handler(di.echoHandler))
http.Handle("/js/", http.FileServer(&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, AssetInfo: AssetInfo, Prefix: "tmpl"}))
http.Handle("/css/", http.FileServer(&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, AssetInfo: AssetInfo, Prefix: "tmpl"}))
http.HandleFunc("/", di.consoleHandler)
go di.logFanOut()
addr := fmt.Sprintf("%s:%d", di.IP, di.Port)
err := http.ListenAndServe(addr, nil)
if err != nil {
log.Fatalf("ListenAndServe: " + err.Error())
}
}