1
0
mirror of https://github.com/gusaul/grpcox.git synced 2024-11-17 06:26:56 +00:00

Merge pull request #26 from gusaul/modify_invoke_piping

change invoke handler directly to bytes buffer
This commit is contained in:
Muhammad Auliya 2020-11-03 09:39:10 +07:00 committed by GitHub
commit 790d251031
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -191,38 +191,17 @@ func (r *Resource) Invoke(ctx context.Context, symbol string, in io.Reader) (str
}
defer r.closeDescriptor()
// because of grpcurl directly fmt.Printf on their invoke function
// 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()
}()
var resultBuffer bytes.Buffer
rf, formatter, err := grpcurl.RequestParserAndFormatterFor(grpcurl.Format("json"), r.descSource, false, true, in)
if err != nil {
return "", 0, err
}
h := grpcurl.NewDefaultEventHandler(os.Stdout, r.descSource, formatter, false)
h := grpcurl.NewDefaultEventHandler(&resultBuffer, r.descSource, formatter, false)
start := time.Now()
err = grpcurl.InvokeRPC(ctx, r.descSource, r.clientConn, symbol, r.headers, h, rf.Next)
end := time.Now().Sub(start) / time.Millisecond
w.Close()
if err != nil {
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())
}
out := <-outC
return out, end, nil
return resultBuffer.String(), end, nil
}
// Close - to close all resources that was opened before