2022-07-10 08:47:12 +00:00
|
|
|
package command
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
)
|
|
|
|
|
|
|
|
type command interface {
|
|
|
|
String() string
|
2022-07-11 18:01:28 +00:00
|
|
|
validateResponse([]byte) ([]byte, error)
|
2022-07-10 08:47:12 +00:00
|
|
|
}
|
|
|
|
|
2022-07-11 18:01:28 +00:00
|
|
|
// Send writes the command to the provided Writer, and reads and validates the
|
|
|
|
// response.
|
|
|
|
//
|
|
|
|
// TODO: accept a context.Context and enforce deadline/timeout.
|
2022-07-10 08:47:12 +00:00
|
|
|
func Send(cmd command, conn io.ReadWriter) ([]byte, error) {
|
|
|
|
_, err := fmt.Fprint(conn, cmd.String())
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("error writing to socket: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
p := make([]byte, 4_096)
|
|
|
|
r := bufio.NewReader(conn)
|
|
|
|
n, err := r.Read(p)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("error reading from socket: %s", err)
|
|
|
|
}
|
|
|
|
|
2022-07-11 18:01:28 +00:00
|
|
|
return cmd.validateResponse(p[:n])
|
2022-07-10 08:47:12 +00:00
|
|
|
}
|