initial commit on github
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
func RegisterLongPollRoutes(r *mux.Router) {
|
||||
r.HandleFunc("/lp", resolveLongPoll).Methods("GET", "OPTIONS", "POST")
|
||||
}
|
||||
|
||||
func resolveLongPoll(w http.ResponseWriter, r *http.Request) {
|
||||
userId, err := GetCurrentUserID(r)
|
||||
if err == ErrNotAuthorized {
|
||||
NoToken.Ferror(w)
|
||||
return
|
||||
}
|
||||
if err == http.ErrNoCookie {
|
||||
NoToken.Ferror(w)
|
||||
return
|
||||
}
|
||||
events, err := lpServer.GetEvents(userId)
|
||||
Response(w, err, events)
|
||||
}
|
||||
|
||||
var NoEventsErr = fmt.Errorf("no events")
|
||||
|
||||
type LongPollServer struct {
|
||||
clients map[uint64]*LongPollClient
|
||||
}
|
||||
|
||||
type LongPollClient struct {
|
||||
events []*LongPollEvent
|
||||
}
|
||||
|
||||
type LongPollEvent struct {
|
||||
Action string `json:"action"`
|
||||
TS int64 `json:"ts"`
|
||||
Payload interface{} `json:"payload"`
|
||||
}
|
||||
|
||||
func InitLongPollServer() *LongPollServer {
|
||||
return &LongPollServer{
|
||||
clients: make(map[uint64]*LongPollClient),
|
||||
}
|
||||
}
|
||||
|
||||
func (lpServer *LongPollServer) PushEvent(payload interface{}, userId uint64, action string) {
|
||||
lpClient, ok := lpServer.clients[userId]
|
||||
if !ok {
|
||||
lpClient = new(LongPollClient)
|
||||
lpServer.clients[userId] = lpClient
|
||||
}
|
||||
|
||||
lpClient.events = append(lpClient.events, &LongPollEvent{
|
||||
action,
|
||||
time.Now().Unix(),
|
||||
payload,
|
||||
})
|
||||
}
|
||||
|
||||
func (lpServer *LongPollServer) PushEventToAll(payload interface{}, action string) {
|
||||
for _, lpClient := range lpServer.clients {
|
||||
lpClient.events = append(lpClient.events, &LongPollEvent{
|
||||
action,
|
||||
time.Now().Unix(),
|
||||
payload,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (lpServer *LongPollServer) GetEvents(userId uint64) ([]*LongPollEvent, error) {
|
||||
lpClient, ok := lpServer.clients[userId]
|
||||
if !ok {
|
||||
lpServer.clients[userId] = new(LongPollClient)
|
||||
return nil, NoEventsErr
|
||||
}
|
||||
|
||||
if len(lpClient.events) == 0 {
|
||||
return nil, NoEventsErr
|
||||
}
|
||||
|
||||
events := lpClient.events
|
||||
lpClient.events = make([]*LongPollEvent, 0)
|
||||
return events, nil
|
||||
}
|
||||
Reference in New Issue
Block a user