diff --git a/server/server.go b/server/server.go index 4e54e1f..3146581 100644 --- a/server/server.go +++ b/server/server.go @@ -18,19 +18,19 @@ const ( ) type Server struct { + baseCtx context.Context mutex *sync.Mutex - channels []wasabi.Channel - addr string http *http.Server - baseCtx context.Context + addr string + channels []wasabi.Channel } -type ServerOption func(*Server) +type Option func(*Server) // NewServer creates new instance of Wasabi server // port - port to listen on // returns new instance of Server -func NewServer(addr string, opts ...ServerOption) *Server { +func NewServer(addr string, opts ...Option) *Server { server := &Server{ addr: addr, channels: make([]wasabi.Channel, 0, 1), @@ -50,9 +50,9 @@ func (s *Server) AddChannel(channel wasabi.Channel) { s.channels = append(s.channels, channel) } -// Run starts server -// ctx - context -// returns error if any +// Run starts the server +// returns error if server is already running +// or if server fails to start func (s *Server) Run() error { if !s.mutex.TryLock() { return fmt.Errorf("server is already running") @@ -86,7 +86,7 @@ func (s *Server) Run() error { // BaseContext optionally specifies based context that will be used for all connections. // If not specified, context.Background() will be used. -func WithBaseContext(ctx context.Context) ServerOption { +func WithBaseContext(ctx context.Context) Option { if ctx == nil { panic("nil context") } diff --git a/server/server_test.go b/server/server_test.go index 9f944ca..7c0a7b1 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -9,6 +9,8 @@ import ( "github.com/ksysoev/wasabi/mocks" ) +type testCtxKey string + func TestNewServer(t *testing.T) { addr := ":8080" server := NewServer(addr) @@ -48,8 +50,7 @@ func TestServer_AddChannel(t *testing.T) { func TestServer_WithBaseContext(t *testing.T) { // Create a new Server instance with a base context - //lint:ignore SA1029 This is a test - ctx := context.WithValue(context.Background(), "test", "test") + ctx := context.WithValue(context.Background(), testCtxKey("test"), "test") server := NewServer(":0", WithBaseContext(ctx)) @@ -58,7 +59,7 @@ func TestServer_WithBaseContext(t *testing.T) { t.Error("Expected non-nil base context") } - if server.baseCtx.Value("test") != "test" { + if server.baseCtx.Value(testCtxKey("test")) != "test" { t.Errorf("Expected context value 'test', but got '%s'", server.baseCtx.Value("test")) } } @@ -70,16 +71,16 @@ func TestServer_Run(t *testing.T) { // Run the server done := make(chan struct{}) go func() { - err := server.Run() - if err != http.ErrServerClosed { + if err := server.Run(); err != http.ErrServerClosed { t.Errorf("Expected error %v, but got %v", http.ErrServerClosed, err) } + close(done) }() - <-time.After(50 * time.Millisecond) - err := server.http.Close() - if err != nil { + <-time.After(100 * time.Millisecond) + + if err := server.http.Close(); err != nil { t.Errorf("Expected no error, but got %v", err) }