-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.go
87 lines (76 loc) · 1.74 KB
/
api.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
package main
import (
"net/http"
"strconv"
"syscall"
"time"
"github.com/gin-gonic/gin"
"github.com/thelegy/koma-bot/sse"
)
func apiStreamJson(conf *Config, clients <-chan sse.Client) func(c *gin.Context) {
return func(c *gin.Context) {
client := <-clients
ch := client.Channel
flusher, ok := c.Writer.(http.Flusher)
if !ok {
return //log error & send some error
}
timeout := time.After(30 * time.Minute)
for i, streamInfo := range conf.StreamInfo {
for _, t := range streamInfo.getTweets() {
if t != nil {
c.SSEvent(MessageTweet+strconv.Itoa(i+1), t)
}
}
}
c.SSEvent("", "")
flusher.Flush()
for {
keepAliveTimer := time.After(55 * time.Second)
select {
case <-timeout:
return
case <-c.Done():
return
case <-keepAliveTimer:
c.Writer.WriteString(":\n\n")
flusher.Flush()
case event := <-ch:
switch msg := event.(type) {
case Tweet:
messageSent := false
for i, streamInfo := range conf.StreamInfo {
if streamInfo.ContainsTweet(msg) {
c.SSEvent(MessageTweet+strconv.Itoa(i+1), msg)
messageSent = true
}
}
if !messageSent {
c.Writer.WriteString(":\n\n")
}
flusher.Flush()
case syscall.Signal:
if msg == syscall.SIGUSR1 {
c.SSEvent(MessageReload, "")
} else {
c.Writer.WriteString(":\n\n")
}
flusher.Flush()
case *Sound:
c.SSEvent(MessageSound, msg.Name)
flusher.Flush()
default:
continue
}
}
}
}
}
func initAPI(conf *Config, clients <-chan sse.Client, engine *gin.Engine) {
engine.GET("/api/v1/stream.json", apiStreamJson(conf, clients))
engine.GET("/ping", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "pong",
})
})
}