5
0
Fork 0
backend-heartbeat/main.go

116 lines
2.6 KiB
Go
Raw Normal View History

2019-02-17 07:47:32 +08:00
package main
import (
"fmt"
"log"
"net/http"
2019-02-18 23:43:11 +08:00
"os"
2019-02-17 07:47:32 +08:00
"strconv"
"time"
2019-02-18 23:43:11 +08:00
"github.com/joho/godotenv"
2019-02-17 07:47:32 +08:00
"github.com/julienschmidt/httprouter"
2019-02-17 08:33:13 +08:00
"github.com/go-redis/redis"
2019-02-17 07:47:32 +08:00
)
var listen string
2019-02-17 08:33:13 +08:00
var redisHost string
2019-02-17 07:47:32 +08:00
type RawClient struct {
UserId string
ClientId string
}
var connections map[RawClient][]chan []byte
2019-02-17 08:33:13 +08:00
var redisClient *redis.Client
2019-02-17 07:47:32 +08:00
func main() {
2019-02-18 23:43:11 +08:00
// Load .env
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
listen = os.Getenv("LISTEN")
redisHost = os.Getenv("REDIS")
2019-02-17 07:47:32 +08:00
connections = make(map[RawClient][]chan []byte)
2019-02-17 08:33:13 +08:00
// Redis
redisClient = redis.NewClient(&redis.Options{
Addr: redisHost,
Password: "",
DB: 0,
})
2019-02-17 07:47:32 +08:00
// Routes
router := httprouter.New()
router.GET("/subscribe/:userid/client/:clientid", Subscribe)
router.POST("/ping/:userid/client/:clientid", PostTime)
// Start server
log.Printf("starting server on %s", listen)
log.Fatal(http.ListenAndServe(listen, router))
}
func Subscribe(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
client := RawClient {
UserId: p.ByName("userid"),
ClientId: p.ByName("clintid"),
}
recv := make(chan []byte)
connections[client] = append(connections[client], recv);
// Refresh connection periodically
resClosed := w.(http.CloseNotifier).CloseNotify()
ticker := time.NewTicker(25 * time.Second)
2019-02-17 08:33:13 +08:00
// Push cached value (if it exists) to the connection
cachedTime, err := redisClient.Get(client.UserId + client.ClientId).Result()
if err == nil {
fmt.Fprintf(w, "data: %s\n\n", cachedTime)
flusher.Flush()
}
2019-02-17 07:47:32 +08:00
for {
select {
case msg := <- recv:
fmt.Fprintf(w, "data: %s\n\n", msg)
flusher.Flush()
case <- ticker.C:
w.Write([]byte(":\n\n"))
case <- resClosed:
ticker.Stop()
delete(connections, client)
return
}
}
}
// TODO: Take client data from token
func PostTime(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
client := RawClient {
UserId: p.ByName("userid"),
ClientId: p.ByName("clientid"),
}
2019-02-17 08:33:13 +08:00
time := []byte(strconv.FormatInt(time.Now().UTC().Unix(), 10)) // UTC Epoch Time in []byte
key := client.UserId + client.ClientId
_ = redisClient.Set(key, time, 0)
2019-02-17 07:47:32 +08:00
for _, connection := range connections[client] {
2019-02-17 08:33:13 +08:00
connection <- time
2019-02-17 07:47:32 +08:00
}
w.WriteHeader(http.StatusOK)
}