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

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,6 +95,7 @@ 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
go func(){
cachedTime, err1 := redisClient.HGet(userId, "time").Result() cachedTime, err1 := redisClient.HGet(userId, "time").Result()
cachedStatus, err2 := redisClient.HGet(userId, "status").Result() cachedStatus, err2 := redisClient.HGet(userId, "status").Result()
if err1 == nil && err2 == nil { if err1 == nil && err2 == nil {
@ -105,11 +107,13 @@ func Subscribe(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
} }
pingBytes, err := json.Marshal(&ping) pingBytes, err := json.Marshal(&ping)
if err == nil { if err == nil {
time.Sleep(1 * time.Second)
fmt.Fprintf(w, "data: %s\n\n", pingBytes) fmt.Fprintf(w, "data: %s\n\n", pingBytes)
flusher.Flush() flusher.Flush()
} }
} }
} }
}()
for { for {
select { select {