1
0
Fork 0
You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

90 lines
1.8 KiB
Go

package main
import (
9 years ago
"encoding/json"
"fmt"
9 years ago
"io/ioutil"
"net/http"
"strings"
"github.com/Bowery/prompt"
"github.com/mkideal/cli"
)
9 years ago
type argT struct {
cli.Helper
Protocol string `cli:"s,scheme" usage:"protocol scheme(http or https)" dft:"http"`
Host string `cli:"H,host" usage:"rqlited host address" dft:"127.0.0.1"`
Port uint16 `cli:"p,port" usage:"rqlited listening http(s) port" dft:"4001"`
}
func main() {
9 years ago
cli.SetUsageStyle(cli.ManualStyle)
cli.Run(new(argT), func(ctx *cli.Context) error {
argv := ctx.Argv().(*argT)
if argv.Help {
ctx.WriteUsage()
return nil
}
prefix := fmt.Sprintf("%s:%d> ", argv.Host, argv.Port)
FOR_READ:
for {
line, err := prompt.Basic(prefix, false)
if err != nil {
return err
}
line = strings.TrimSpace(line)
if line == "" {
continue
}
var (
index = strings.Index(line, " ")
cmd = line
)
if index >= 0 {
cmd = line[:index]
}
cmd = strings.ToUpper(cmd)
switch cmd {
case "QUIT", "EXIT":
break FOR_READ
case "SELECT":
err = query(ctx, cmd, line, argv)
default:
err = execute(ctx, cmd, line, argv)
}
if err != nil {
ctx.String("%s %v\n", ctx.Color().Red("ERR!"), err)
}
}
ctx.String("bye~\n")
return nil
})
}
func makeJSONBody(line string) string {
data, err := json.MarshalIndent([]string{line}, "", " ")
if err != nil {
return ""
}
return string(data)
}
func sendRequest(ctx *cli.Context, urlStr string, line string, ret interface{}) error {
data := makeJSONBody(line)
resp, err := http.Post(urlStr, "application/json", strings.NewReader(data))
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if err := json.Unmarshal(body, ret); err != nil {
return fmt.Errorf(string(body))
}
return nil
}