/
notification_handlers.go
70 lines (59 loc) · 1.31 KB
/
notification_handlers.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
package notifications
import (
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"go.uber.org/zap"
)
type NotificationHandlers struct {
service *NotificationService
log *zap.Logger
}
func NewNotificationHandlers(service *NotificationService, log *zap.Logger) *NotificationHandlers {
return &NotificationHandlers{service: service, log: log}
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 4096,
WriteBufferSize: 4096,
EnableCompression: true,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func (h *NotificationHandlers) Reader(c *gin.Context) {
ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
fmt.Println(err)
return
}
defer ws.Close()
for {
//mt, message, err := ws.ReadMessage()
// if err != nil {
// fmt.Println(err)
// break
// }
// fmt.Println("read", string(message))
notifications, err := h.service.repository.GetAllNotRead(c.Request.Context())
if err != nil {
fmt.Println(err)
break
}
for _, notification := range notifications {
n, err := json.Marshal(notification)
if err != nil {
fmt.Println(err)
break
}
err = ws.WriteMessage(websocket.TextMessage, n)
if err != nil {
fmt.Println(err)
break
}
}
time.Sleep(5 * time.Second)
}
}