Private
Public Access
1
0

server: implements /updates websocket

This commit is contained in:
2023-08-13 00:33:46 -07:00
parent e9a9d1c064
commit b92d1a2892
4 changed files with 122 additions and 1 deletions

View File

@@ -12,6 +12,7 @@ import (
"code.severnaya.net/kordophone-mock/v2/server"
"github.com/google/uuid"
"github.com/rs/zerolog/log"
"golang.org/x/net/websocket"
)
type MockHTTPServerConfiguration struct {
@@ -286,6 +287,21 @@ func (m *MockHTTPServer) handleMarkConversation(w http.ResponseWriter, r *http.R
w.WriteHeader(http.StatusOK)
}
func (m *MockHTTPServer) handleUpdatesWebsocket(c *websocket.Conn) {
// Fetch updates continuously
for {
// Fetch updates (blocking)
updates := m.Server.FetchUpdatesBlocking(-1)
// Send updates to client
err := websocket.JSON.Send(c, updates)
if err != nil {
log.Error().Err(err).Msg("handleUpdatesWebsocket: Error sending updates to client (probably disconnected)")
return
}
}
}
func (m *MockHTTPServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
m.logRequest(r, r.URL.Query().Encode())
m.mux.ServeHTTP(w, r)
@@ -307,6 +323,12 @@ func NewMockHTTPServer(config MockHTTPServerConfiguration) *MockHTTPServer {
this.mux.Handle("/sendMessage", http.HandlerFunc(this.handleSendMessage))
this.mux.Handle("/markConversation", http.HandlerFunc(this.handleMarkConversation))
// /updates websocket
this.mux.Handle("/updates", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s := websocket.Server{Handler: websocket.Handler(this.handleUpdatesWebsocket)}
s.ServeHTTP(w, r)
}))
this.mux.Handle("/", http.HandlerFunc(this.handleNotFound))
return &this