1
0
mirror of https://github.com/gusaul/grpcox.git synced 2024-12-26 02:40:10 +00:00

change invoke handler directly to bytes buffer

This commit is contained in:
gusaul 2020-11-03 09:37:50 +07:00
parent 8aa67b6529
commit ec4ba2090d

View File

@ -191,38 +191,17 @@ func (r *Resource) Invoke(ctx context.Context, symbol string, in io.Reader) (str
} }
defer r.closeDescriptor() defer r.closeDescriptor()
// because of grpcurl directly fmt.Printf on their invoke function var resultBuffer bytes.Buffer
// so we stub the Stdout using os.Pipe
backUpStdout := os.Stdout
defer func() {
os.Stdout = backUpStdout
}()
f, w, err := os.Pipe()
if err != nil {
return "", 0, err
}
os.Stdout = w
// copy the output in a separate goroutine so printing can't block indefinitely
outC := make(chan string, 1)
var buf bytes.Buffer
go func() {
io.Copy(&buf, f)
outC <- buf.String()
f.Close()
}()
rf, formatter, err := grpcurl.RequestParserAndFormatterFor(grpcurl.Format("json"), r.descSource, false, true, in) rf, formatter, err := grpcurl.RequestParserAndFormatterFor(grpcurl.Format("json"), r.descSource, false, true, in)
if err != nil { if err != nil {
return "", 0, err return "", 0, err
} }
h := grpcurl.NewDefaultEventHandler(os.Stdout, r.descSource, formatter, false) h := grpcurl.NewDefaultEventHandler(&resultBuffer, r.descSource, formatter, false)
start := time.Now() start := time.Now()
err = grpcurl.InvokeRPC(ctx, r.descSource, r.clientConn, symbol, r.headers, h, rf.Next) err = grpcurl.InvokeRPC(ctx, r.descSource, r.clientConn, symbol, r.headers, h, rf.Next)
end := time.Now().Sub(start) / time.Millisecond end := time.Now().Sub(start) / time.Millisecond
w.Close()
if err != nil { if err != nil {
return "", end, err return "", end, err
} }
@ -231,9 +210,7 @@ func (r *Resource) Invoke(ctx context.Context, symbol string, in io.Reader) (str
return "", end, fmt.Errorf(h.Status.Message()) return "", end, fmt.Errorf(h.Status.Message())
} }
out := <-outC return resultBuffer.String(), end, nil
return out, end, nil
} }
// Close - to close all resources that was opened before // Close - to close all resources that was opened before