-
Notifications
You must be signed in to change notification settings - Fork 11
/
main.go
134 lines (118 loc) · 2.52 KB
/
main.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package main
import (
"html/template"
"time"
"github.com/admpub/log"
"github.com/admpub/sockjs-go/v3/sockjs"
"github.com/webx-top/echo"
"github.com/webx-top/echo/engine/fasthttp"
"github.com/webx-top/echo/engine/standard"
ws "github.com/webx-top/echo/handler/sockjs"
mw "github.com/webx-top/echo/middleware"
)
var homeTemplate = template.Must(template.New("").Parse(`
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Chat : <input id='chat' type='text' value='' size='20'/>
<button onclick="sent()">Sent</button>
<div id='content'></div>
<script src="{{.sockjs}}"></script>
<script>
function $D(tag){
return document.createElement(tag||'div');
}
function $A(ele, father){
father = father || document.body;
father.appendChild(ele);
}
function $(tag){
return document.getElementById(tag);
}
function I(ele, str){
ele.innerHTML = str||'';
}
function showMsg(msg){
I($('content'), $('content').innerHTML + '<br >' + msg);
}
function sent(){
ws.send($('chat').value);
}
var ws = new SockJS('{{.echo}}');
ws.onopen = function(){
showMsg('onopen');
};
ws.onclose = function(){
showMsg('onclose');
};
ws.onmessage = function(msg){
showMsg(msg.data);
};
</script>
</body>
</html>
`))
func main() {
e := echo.New()
e.Use(mw.Log())
e.Get("/", func(c echo.Context) error {
homeTemplate.Execute(c.Response(), map[string]string{
"echo": "http://" + c.Request().Host() + "/websocket",
"sockjs": sockjs.DefaultOptions.SockJSURL,
"notice": "http://" + c.Request().Host() + "/notice",
})
return nil
})
options := ws.Options{
Handle: func(c sockjs.Session) error {
//push(writer)
go func() {
var counter int
for {
if counter >= 10 { //测试只推10条
return
}
time.Sleep(5 * time.Second)
message := time.Now().String()
log.Info(`Push message: `, message)
if err := c.Send(message); err != nil {
log.Error(`Push error: `, err.Error())
return
}
counter++
}
}()
// */
//echo
ws.DefaultExecuter(c)
return nil
},
Options: &sockjs.DefaultOptions,
Prefix: "/websocket",
}
options.Wrapper(e)
options.Handle = func(c sockjs.Session) error {
for {
time.Sleep(5 * time.Second)
message := time.Now().String()
log.Info(`Push message: `, message)
if err := c.Send(message); err != nil {
return err
}
}
return nil
}
options.Prefix = "/notice"
options.Wrapper(e)
switch `` {
case `fast`:
panic(`Unimplemented`)
// FastHTTP
e.Run(fasthttp.New(":4444"))
default:
// Standard
e.Run(standard.New(":4444"))
}
}