Implement Go bindings for pipe io client

This commit is contained in:
Kristóf Tóth 2019-04-09 17:07:46 +02:00
parent 61eb57c918
commit deafc516bd
2 changed files with 121 additions and 0 deletions

101
clients/go/pipeio/pipeio.go Normal file
View File

@ -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
}

20
clients/go/test.go Normal file
View File

@ -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()
}