diff --git a/echovault/echovault.go b/echovault/echovault.go index 10d2dae..e7fe359 100644 --- a/echovault/echovault.go +++ b/echovault/echovault.go @@ -399,6 +399,13 @@ func (server *EchoVault) handleConnection(conn net.Conn) { ctx := context.WithValue(server.context, internal.ContextConnID("ConnectionID"), fmt.Sprintf("%s-%d", server.context.Value(internal.ContextServerID("ServerID")), cid)) + defer func() { + log.Printf("closing connection %d...", cid) + if err := conn.Close(); err != nil { + log.Println(err) + } + }() + for { message, err := internal.ReadMessage(r) @@ -414,11 +421,9 @@ func (server *EchoVault) handleConnection(conn net.Conn) { } res, err := server.handleCommand(ctx, message, &conn, false, false) - if err != nil && errors.Is(err, io.EOF) { break } - if err != nil { if _, err = w.Write([]byte(fmt.Sprintf("-Error %s\r\n", err.Error()))); err != nil { log.Println(err) @@ -428,7 +433,7 @@ func (server *EchoVault) handleConnection(conn net.Conn) { chunkSize := 1024 - // If the length of the response is 0, return nothing to the client + // If the length of the response is 0, return nothing to the client. if len(res) == 0 { continue } @@ -456,10 +461,6 @@ func (server *EchoVault) handleConnection(conn net.Conn) { startIndex += chunkSize } } - - if err := conn.Close(); err != nil { - log.Println(err) - } } // Start starts the EchoVault instance's TCP listener. diff --git a/echovault/modules.go b/echovault/modules.go index d3e3974..973bea1 100644 --- a/echovault/modules.go +++ b/echovault/modules.go @@ -21,6 +21,7 @@ import ( "github.com/echovault/echovault/internal" "github.com/echovault/echovault/internal/clock" "github.com/echovault/echovault/internal/constants" + "io" "net" "strings" ) @@ -74,6 +75,11 @@ func (server *EchoVault) handleCommand(ctx context.Context, message []byte, conn return nil, errors.New("empty command") } + // If quit command is passed, EOF error. + if strings.EqualFold(cmd[0], "quit") { + return nil, io.EOF + } + command, err := server.getCommand(cmd[0]) if err != nil { return nil, err diff --git a/internal/modules/acl/commands_test.go b/internal/modules/acl/commands_test.go index 9fc9513..83897a1 100644 --- a/internal/modules/acl/commands_test.go +++ b/internal/modules/acl/commands_test.go @@ -62,7 +62,7 @@ func setUpServer(bindAddr string, port uint16, requirePass bool, aclConfig strin echovault.WithConfig(conf), ) - // Add the initial test users to the ACL module + // Add the initial test users to the ACL module. // a.AddUsers(generateInitialTestUsers()) return mockServer