diff --git a/clients/go/pipeio/pipeio.go b/clients/go/pipeio/pipeio.go new file mode 100644 index 0000000..83f2403 --- /dev/null +++ b/clients/go/pipeio/pipeio.go @@ -0,0 +1,101 @@ +package pipeio + +import ( + "os" + "bufio" +) + + +type pipeReader struct { + pipe *os.File + scanner *bufio.Scanner +} + +func NewPipeReader(pipePath string) (*pipeReader, error) { + pipe, err := os.Open(pipePath) + scanner := bufio.NewScanner(pipe) + scanner.Split(bufio.ScanLines) + if err != nil { + return nil, err + } + return &pipeReader{ + pipe: pipe, + scanner: scanner, + }, nil +} + +func (preader *pipeReader) RecvMessage() []byte { + if preader.scanner.Scan() { + return preader.scanner.Bytes() + } + return nil +} + +func (preader *pipeReader) Close() { + preader.pipe.Close() +} + + +type pipeWriter struct { + pipe *os.File +} + +func NewPipeWriter(pipePath string) (*pipeWriter, error) { + pipe, err := os.OpenFile(pipePath, os.O_WRONLY, 0644) + if err != nil { + return nil, err + } + return &pipeWriter{pipe: pipe}, nil +} + +func (pwriter *pipeWriter) Close() { + pwriter.pipe.Close() +} + +func (pwriter *pipeWriter) SendMessage(msg []byte) { + pwriter.pipe.Write(append(msg, '\n')) +} + + +type pipeIO struct { + Reader pipeReader + Writer pipeWriter + handleMessage handleMessageFunc +} + +type handleMessageFunc func([]byte) + +func NewPipeIO(inPipePath, outPipePath string) (*pipeIO, error) { + reader, err := NewPipeReader(inPipePath) + if err != nil { + return nil, err + } + writer, err := NewPipeWriter(outPipePath) + if err != nil { + return nil, err + } + return &pipeIO{ + Reader: *reader, + Writer: *writer, + handleMessage: func([]byte){}, + }, nil +} + +func (pipeio *pipeIO) Close() { + pipeio.Reader.Close() + pipeio.Writer.Close() +} + +func (pipeio *pipeIO) Run() { + for { + msg := pipeio.Reader.RecvMessage() + if msg == nil { + break + } + pipeio.handleMessage(msg) + } +} + +func (pipeio *pipeIO) HandleMessage(fun handleMessageFunc) { + pipeio.handleMessage = fun +} diff --git a/clients/go/test.go b/clients/go/test.go new file mode 100644 index 0000000..8ea1eb5 --- /dev/null +++ b/clients/go/test.go @@ -0,0 +1,20 @@ +package main + +import ( + "log" + "./pipeio" +) + + +func main() { + pipeio, err := pipeio.NewPipeIO("in", "out") + if err != nil { + log.Fatal(err) + } + defer pipeio.Close() + + pipeio.HandleMessage(func(msg []byte) { + pipeio.Writer.SendMessage(msg) + }) + pipeio.Run() +}