From 2cb2a300fb081ed348153e00322ef2e0c770d2e8 Mon Sep 17 00:00:00 2001 From: UnicodingUnicorn <7555ic@gmail.com> Date: Sun, 17 Feb 2019 07:47:32 +0800 Subject: [PATCH] Initial commit --- README.md | 52 ++++++++++++++++++++++++++++++- main.go | 91 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 142 insertions(+), 1 deletion(-) create mode 100644 main.go diff --git a/README.md b/README.md index 77a8fbd..d23d648 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,53 @@ # backend-heartbeat -Beep backend records and makes available the last seen times of users. \ No newline at end of file +Beep backend records and makes available the last seen times of users. + +## API + +### Subscribe User + +``` +GET /subscribe/:userid/client/:clientid +``` + +Subscribe to a user. Every time a user pings this service, the time will be sent to all subscribed users. + +```js +const es = new EventSource(`${host}/subscribe/${user}/client/${device}`); +es.onmessage = (e) => { + const timestamp = e.data; + // Do whatever with the timestamp +}; +``` + +#### URL Params + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| userid | String | Target user's ID. | ✓ | +| clientid | String | Target user's device's ID. | ✓ | + +#### Success Response (200 OK) + +An [EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) stream. + +--- + +### Ping Server + +``` +POST /ping/:userid/client/:clientid +``` + +Ping the server. + +#### URL Params + +| Name | Type | Description | Required | +| ---- | ---- | ----------- | -------- | +| userid | String | User's ID. | ✓ | +| clientid | String | User's device's ID. | ✓ | + +#### Success Response (200 OK) + +Empty body. diff --git a/main.go b/main.go new file mode 100644 index 0000000..3f5e455 --- /dev/null +++ b/main.go @@ -0,0 +1,91 @@ +package main + +import ( + "flag" + "fmt" + "log" + "net/http" + "strconv" + "time" + + "github.com/julienschmidt/httprouter" +) + +var listen string + +type RawClient struct { + UserId string + ClientId string +} + +var connections map[RawClient][]chan []byte + +func main() { + // Parse flags + flag.StringVar(&listen, "listen", ":8080", "host and port to listen on") + flag.Parse() + + connections = make(map[RawClient][]chan []byte) + + // 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) + + 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"), + } + + time := time.Now().UTC().Unix() + + for _, connection := range connections[client] { + connection <- []byte(strconv.FormatInt(time, 10)) + } + + w.WriteHeader(http.StatusOK) +}