warren/cmd/warrend/main.go

92 lines
1.6 KiB
Go

package main
import (
"fmt"
"github.com/dballard/warren/lib/warren"
"log"
"net"
"os"
"os/signal"
"strings"
"syscall"
)
type SockCommand struct {
warren.Command
Run func(cmd *SockCommand, c net.Conn, args ...string)
}
func (cmd *SockCommand) GetName() string {
return cmd.Name
}
func (cmd *SockCommand) Exec(c net.Conn, args []string) {
cmd.Flag.Usage = func() {
// helpFunc(c, c.Name)
}
cmd.Flag.Parse(args)
cmd.Run(cmd, c, cmd.Flag.Args()...)
}
func sockCmdHandle(c net.Conn) {
defer c.Close()
fmt.Println("cmdHandle")
data, err := warren.ReadStringz(c)
if err != nil {
fmt.Println(err)
warren.WriteStringz(c, "read error:"+err.Error())
return
}
fmt.Println("cmdHandle got command:", string(data))
// BAD: TODO: handle quotes "
var args = strings.Split(data, " ")
// parse args
var icmd = warren.GetCommand(args[0])
// get and run cmd
if icmd == nil {
warren.WriteStringz(c, "Unknown command "+args[0])
// usage ?
return
}
icmd.(*SockCommand).Exec(c, args[1:])
warren.WriteStringz(c, "echo: "+data)
}
func main() {
warren.RegisterCommand(statusCmd)
cmdSock, err := net.Listen(warren.CmdSockType(), warren.CmdSockAddr())
if cmdSock != nil {
defer cmdSock.Close()
}
if err != nil {
log.Fatal("Listen on sock error:", err)
}
// Handle signals
c := make(chan os.Signal, 1)
signal.Notify(c,
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGQUIT,
syscall.SIGHUP,
)
go func() {
_ = <-c
cmdSock.Close()
}()
for {
fd, err := cmdSock.Accept()
fmt.Println("accept")
if err != nil {
log.Fatal("accpet error:", err)
}
go sockCmdHandle(fd)
}
}