Skip to content

Commit

Permalink
Merge pull request #58 from KianYang-Lee/ky-add-chan-to-signify-serve…
Browse files Browse the repository at this point in the history
…r-readiness

Add channel to signify server readiness
  • Loading branch information
ksysoev authored May 31, 2024
2 parents 5f59121 + 67275b3 commit 95d6173
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 23 deletions.
15 changes: 15 additions & 0 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,20 @@ type Server struct {
handler *http.Server
addr string
channels []wasabi.Channel
ready chan<- struct{}
}

type Option func(*Server)

// WithReadinessChan sets ch to [Server] and will be closed once the [Server] is
// ready to accept connection. Typically used in testing after calling [Run]
// method and waiting for ch to close, before continuing with test logics.
func WithReadinessChan(ch chan<- struct{}) Option {
return func(s *Server) {
s.ready = ch
}
}

// NewServer creates new instance of Wasabi server
// port - port to listen on
// returns new instance of Server
Expand Down Expand Up @@ -99,6 +109,11 @@ func (s *Server) Run() (err error) {

slog.Info("Starting app server on " + s.listener.Addr().String())

// Signals that server can accept connections
if s.ready != nil {
close(s.ready)
}

err = s.handler.Serve(s.listener)

if err != nil && err != http.ErrServerClosed {
Expand Down
32 changes: 9 additions & 23 deletions server/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,8 @@ func TestServer_Close_NoContext(t *testing.T) {

func TestServer_Addr(t *testing.T) {
// Create a new Server instance
server := NewServer(":0")
done := make(chan struct{})
server := NewServer(":0", WithReadinessChan(done))
defer server.Close()

Check failure on line 232 in server/server_test.go

View workflow job for this annotation

GitHub Actions / tests

only one cuddle assignment allowed before defer statement (wsl)

// Create a mock channel
Expand All @@ -243,30 +244,15 @@ func TestServer_Addr(t *testing.T) {
}

// Start the server in a separate goroutine
done := make(chan struct{})

// Run the server
for i := 0; i < 2; i++ {
go func() {
err := server.Run()
switch err {
case nil:
case ErrServerAlreadyRunning:
close(done)
default:
t.Errorf("Got unexpected error: %v", err)
}
}()
}

select {
case <-done:
case <-time.After(1 * time.Second):
t.Error("Expected server to start")
}
go func() {
err := server.Run()
if err != nil {
t.Errorf("Got unexpected error: %v", err)
}
}()

// Wait for the server to fully start
time.Sleep(1 * time.Millisecond)
<-done

addr := server.Addr()

Expand Down

0 comments on commit 95d6173

Please sign in to comment.