migration to chi

This commit is contained in:
2025-03-12 16:30:40 +03:00
parent ae81fbcce9
commit 45bb32e7a6
46 changed files with 1352 additions and 1323 deletions
+90
View File
@@ -0,0 +1,90 @@
package routes
import (
"backend/database"
"errors"
"fmt"
"github.com/go-chi/chi/v5"
"net/http"
"time"
)
func RegisterLongPollRoutes(r chi.Router) {
r.Get("/", resolveLongPoll)
}
func resolveLongPoll(w http.ResponseWriter, r *http.Request) {
userId, err := GetCurrentUserID(r)
if errors.Is(err, database.ErrNotAuthorized) {
NoToken.Ferror(w)
return
}
if errors.Is(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
}