simplFT/server/server/parser.go

88 lines
1.7 KiB
Go
Raw Normal View History

2017-10-20 15:08:25 +00:00
package server
import (
"net"
"strings"
)
// checkArgumentsLength returns an error if length is not equal to expected.
func checkArgumentsLength(length int, expected int) error {
if length > expected {
return TooManyArguments
} else if length < expected {
return TooFewArguments
}
return nil
}
func ProcessInput(c net.Conn, text string) error {
commands := strings.Fields(text)
commandsLen := len(commands)
// Possibly empty input, just go on.
if commandsLen == 0 {
return nil
}
thisCommand := commands[0]
switch thisCommand {
2017-10-20 15:08:25 +00:00
case "get":
// Check arguments
err := checkArgumentsLength(commandsLen, 2)
if err != nil {
return &InputError{thisCommand, err}
2017-10-20 15:08:25 +00:00
}
// Get the file
2017-10-20 15:34:16 +00:00
_, err = GetFile(c, commands[1])
2017-10-20 15:08:25 +00:00
if err != nil {
return &InputError{thisCommand, err}
2017-10-20 15:08:25 +00:00
}
case "ls":
// Check arguments
err := checkArgumentsLength(commandsLen, 1)
if err != nil {
return &InputError{thisCommand, err}
2017-10-20 15:08:25 +00:00
}
err = ListFiles(c)
if err != nil {
return &InputError{thisCommand, err}
2017-10-20 15:08:25 +00:00
}
case "clear":
// Check arguments
err := checkArgumentsLength(commandsLen, 1)
if err != nil {
return &InputError{thisCommand, err}
2017-10-20 15:08:25 +00:00
}
// Ansi clear: 1b 5b 48 1b 5b 4a
// clear | hexdump -C
var b []byte = []byte{0x1b, 0x5b, 0x48, 0x1b, 0x5b, 0x4a}
2017-10-20 15:20:11 +00:00
2017-10-20 15:08:25 +00:00
c.Write(b)
2017-10-20 15:20:11 +00:00
case "help":
// Check arguments
err := checkArgumentsLength(commandsLen, 1)
if err != nil {
return &InputError{thisCommand, err}
2017-10-20 15:20:11 +00:00
}
err = ShowHelp(c)
if err != nil {
return &InputError{thisCommand, err}
2017-10-20 15:20:11 +00:00
}
2017-10-20 15:08:25 +00:00
case "exit":
err := checkArgumentsLength(commandsLen, 1)
if err != nil {
return &InputError{thisCommand, err}
2017-10-20 15:08:25 +00:00
}
c.Close()
default:
return &InputError{thisCommand, InvalidCommand}
2017-10-20 15:08:25 +00:00
}
return nil
}