-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
110 lines (90 loc) · 2.15 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
package main
import (
"context"
"fmt"
"net/http"
"time"
"github.com/gorilla/websocket"
"github.com/labstack/echo/v4"
"github.com/paulfarver/mocksocket/producer"
"github.com/sirupsen/logrus"
)
type WebsocketHandler struct {
upgrader *websocket.Upgrader
logger *logrus.Logger
}
func main() {
w := WebsocketHandler{
upgrader: &websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { return true },
},
logger: logrus.New(),
}
e := echo.New()
e.GET("/sequence/:sequence/delay/:delay", w.HandleWebsocket)
e.Logger.Fatal(e.Start(":8080"))
}
type Request struct {
Sequence string `param:"sequence"`
Delay string `param:"delay"`
}
func (w *WebsocketHandler) HandleWebsocket(ctx echo.Context) error {
req := Request{}
if err := ctx.Bind(&req); err != nil {
return err
}
delay, err := time.ParseDuration(req.Delay)
if err != nil {
return err
}
w.logger.Infof("Handling websocket request for sequence %s and delay %s", req.Sequence, delay)
conn, err := w.upgrader.Upgrade(ctx.Response(), ctx.Request(), nil)
if err != nil {
w.logger.WithError(err).Error("Failed to upgrade connection")
return err
}
defer conn.Close()
conn.SetCloseHandler(func(code int, text string) error {
fmt.Println("close handler")
return nil
})
c, cancel := context.WithCancel(ctx.Request().Context())
defer cancel()
seq, err := producer.GetSequence(req.Sequence)
if err != nil {
w.logger.WithError(err).Warn("failed to get sequence. Defaulting to random")
}
producer := producer.Producer{
Delay: delay,
Sequence: seq,
}
ch, closer := producer.Produce()
defer closer()
go func() {
for {
if _, _, err := conn.ReadMessage(); err != nil {
cancel()
return
}
}
}()
for {
select {
case msg, ok := <-ch:
if !ok {
w.logger.Info("producer channel closed")
return nil
}
w.logger.WithField("msg", msg).Info("Sending message to client")
if err := conn.WriteJSON(msg); err != nil {
w.logger.WithError(err).Error("Error sending message to client")
return err
}
case <-c.Done():
w.logger.Info("context canceled")
return nil
}
}
}