Added array serialization to encode function. Moved message reading to utils packages as it's used by both server and client

This commit is contained in:
Kelvin Clement Mwinuka
2023-07-01 21:59:41 +08:00
parent eb188deb7b
commit ef140c8427
5 changed files with 103 additions and 60 deletions

View File

@@ -29,7 +29,6 @@ func encodeError(wr *resp.Writer, tokens []string) {
}
func encodeSimpleString(wr *resp.Writer, tokens []string) error {
fmt.Println(tokens, len(tokens))
switch len(tokens) {
default:
return fmt.Errorf(wrong_args_error, strings.ToUpper(tokens[0]))
@@ -40,6 +39,23 @@ func encodeSimpleString(wr *resp.Writer, tokens []string) error {
}
}
func encodeArray(wr *resp.Writer, tokens []string) error {
switch l := len(tokens); {
default:
return fmt.Errorf(wrong_args_error, strings.ToUpper(tokens[0]))
case l > 0:
arr := []resp.Value{}
for _, token := range tokens[1:] {
arr = append(arr, resp.AnyValue(token))
}
wr.WriteArray(arr)
return nil
}
}
func encodePingPong(wr *resp.Writer, tokens []string) error {
switch len(tokens) {
default:
@@ -171,6 +187,8 @@ func Encode(buf io.ReadWriter, comm string) error {
err = encodeIncr(wr, tokens)
case "simplestring":
err = encodeSimpleString(wr, tokens)
case "array":
err = encodeArray(wr, tokens)
case "Error":
encodeError(wr, tokens)
err = errors.New("failed to parse command")