Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: server should start the receive loop #19

Merged
merged 1 commit into from
Dec 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,6 @@ func realMain() int {
return 1
}

go sarc.ReceiveLoop()

srv := server.New(sarc)

server := &http.Server{
Expand Down
4 changes: 2 additions & 2 deletions receiver/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,15 +110,15 @@ func New(uri *url.URL) (*Client, error) {
// ReceiveLoop is a blocking call and it loop over receiving messages over the
// websocket and record them internally to be consumed by either Pop() or
// Flush().
func (c *Client) ReceiveLoop() {
func (c *Client) ReceiveLoop() error {
log.Print("Starting the receive loop from Signal API")

for {
_, msg, err := c.ReadMessage()
if err != nil {
log.Printf("error returned by the websocket: %s", err)

return
return err
}

c.recordMessage(msg)
Expand Down
15 changes: 14 additions & 1 deletion server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package server
import (
"encoding/json"
"fmt"
"log"
"net/http"

"github.com/kalbasit/signal-api-receiver/receiver"
Expand All @@ -19,13 +20,25 @@ type Server struct {
}

type client interface {
ReceiveLoop() error
Pop() *receiver.Message
Flush() []receiver.Message
}

// New returns a new Server.
func New(sarc client) *Server {
return &Server{sarc: sarc}
s := &Server{sarc: sarc}
go s.start()

return s
}

func (s *Server) start() {
for {
if err := s.sarc.ReceiveLoop(); err != nil {
log.Printf("Error in the receive loop: %v", err)
}
}
}

// ServeHTTP implements the http.Handler interface
Expand Down
4 changes: 4 additions & 0 deletions server/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ type mockClient struct {
msgs []receiver.Message
}

func (mc *mockClient) ReceiveLoop() error {
return nil
}

func (mc *mockClient) Pop() *receiver.Message {
if len(mc.msgs) == 0 {
return nil
Expand Down
Loading