-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path14.go
68 lines (55 loc) · 1.22 KB
/
14.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
package main
import (
"fmt"
"log"
"net/http"
"os"
"strings"
"text/template"
"golang.org/x/net/websocket"
)
const LAUNCH_FAILED = 1
const FILE_READ = 2
const BAD_TEMPLATE = 3
const ADDRESS = ":3000"
type PageConfiguration struct {
URL string
Commands []string
}
func main() {
p := PageConfiguration{"/socket", []string{"A", "B", "C"}}
html, e := template.ParseFiles(BaseName() + ".html")
Abort(FILE_READ, e)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
Abort(BAD_TEMPLATE, html.Execute(w, p))
})
http.Handle(p.URL, websocket.Handler(func(ws *websocket.Conn) {
defer func() {
if e := ws.Close(); e != nil {
log.Println(e.Error())
}
}()
var b struct{ Message string }
for {
if e := websocket.JSON.Receive(ws, &b); e == nil {
log.Printf("received: %v\n", b.Message)
websocket.JSON.Send(ws, []interface{}{b.Message})
} else {
log.Printf("socket receive error: %v\n", e)
break
}
}
}))
Abort(LAUNCH_FAILED, http.ListenAndServe(ADDRESS, nil))
}
func Abort(n int, e error) {
if e != nil {
fmt.Println(e)
os.Exit(n)
}
}
func BaseName() string {
s := strings.Split(os.Args[0], "/")
return s[len(s)-1]
}