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 }