server: implements /updates websocket
This commit is contained in:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user