5
0
Fork 0

WriteHeader and add a delay to push last seen

master
Daniel Lim 2019-06-23 09:15:26 +08:00
parent 9b84f4c9ac
commit d5828f96f4
1 changed files with 19 additions and 15 deletions

34
main.go
View File

@ -79,6 +79,7 @@ func Subscribe(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
w.Header().Set("Content-Type", "text/event-stream") w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache") w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive") w.Header().Set("Connection", "keep-alive")
w.WriteHeader(200)
userId := p.ByName("userid") userId := p.ByName("userid")
@ -94,26 +95,29 @@ func Subscribe(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
ticker := time.NewTicker(25 * time.Second) ticker := time.NewTicker(25 * time.Second)
// Push cached value (if it exists) to the connection // Push cached value (if it exists) to the connection
cachedTime, err1 := redisClient.HGet(userId, "time").Result() go func(){
cachedStatus, err2 := redisClient.HGet(userId, "status").Result() cachedTime, err1 := redisClient.HGet(userId, "time").Result()
if err1 == nil && err2 == nil { cachedStatus, err2 := redisClient.HGet(userId, "status").Result()
uintTime, err3 := strconv.ParseInt(cachedTime, 10, 64) if err1 == nil && err2 == nil {
if err3 != nil { uintTime, err3 := strconv.ParseInt(cachedTime, 10, 64)
ping := Ping { if err3 != nil {
Time: uintTime, ping := Ping {
Status: cachedStatus, Time: uintTime,
} Status: cachedStatus,
pingBytes, err := json.Marshal(&ping) }
if err == nil { pingBytes, err := json.Marshal(&ping)
fmt.Fprintf(w, "data: %s\n\n", pingBytes) if err == nil {
flusher.Flush() time.Sleep(1 * time.Second)
fmt.Fprintf(w, "data: %s\n\n", pingBytes)
flusher.Flush()
}
} }
} }
} }()
for { for {
select { select {
case msg := <- recv: case msg := <-recv:
fmt.Fprintf(w, "data: %s\n\n", msg) fmt.Fprintf(w, "data: %s\n\n", msg)
flusher.Flush() flusher.Flush()
case <- ticker.C: case <- ticker.C: