-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroute.go
80 lines (68 loc) · 1.55 KB
/
route.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
package logportalapi
import (
"encoding/json"
"io"
"log"
"time"
"github.com/gin-gonic/gin"
)
func RegisterRoute(handler *gin.Engine) *SSEEvent {
stream := getNewSSEServer()
handler.GET(
"/log-portal/stream",
addHeaders(),
stream.serveHTTP(),
getStream,
)
handler.Use(loggingMiddleware(stream))
return stream
}
func getStream(c *gin.Context) {
v, ok := c.Get("clientChan")
if !ok {
return
}
clientChan, ok := v.(clientChan)
if !ok {
return
}
c.Stream(func(w io.Writer) bool {
// Stream message to client from message channel
if msg, ok := <-clientChan; ok {
c.SSEvent("message", msg)
return true
}
return false
})
}
func addHeaders() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Content-Type", "text/event-stream")
c.Writer.Header().Set("Cache-Control", "no-cache")
c.Writer.Header().Set("Connection", "keep-alive")
c.Writer.Header().Set("Transfer-Encoding", "chunked")
c.Next()
}
}
func loggingMiddleware(stream *SSEEvent) gin.HandlerFunc {
return func(c *gin.Context) {
startTime := time.Now()
c.Next()
responseTime := time.Since(startTime)
logMessage := LogMessage{
TimeStamp: time.Now().Format("2006-01-02 15:04:05"),
Status: c.Writer.Status(),
Method: c.Request.Method,
Path: c.Request.URL.Path,
Type: "gin",
ResponseTime: responseTime.String(),
}
// Convert to JSON
jsonData, err := json.Marshal(logMessage)
if err != nil {
log.Printf("JSON encoding error: %s", err)
return
}
stream.Message <- jsonData
}
}