Skip to content

Commit b0be3cd

Browse files
emcfarlaneachew22
authored andcommitted
runtime: fix chunk encoding
1 parent 82b83c7 commit b0be3cd

File tree

2 files changed

+68
-1
lines changed

2 files changed

+68
-1
lines changed

runtime/handler.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ func ForwardResponseStream(ctx context.Context, mux *ServeMux, marshaler Marshal
5858
grpclog.Printf("Failed to marshal response chunk: %v", err)
5959
return
6060
}
61-
if _, err = fmt.Fprintf(w, "%s\n", buf); err != nil {
61+
if _, err = w.Write(buf); err != nil {
6262
grpclog.Printf("Failed to send response chunk: %v", err)
6363
return
6464
}

runtime/handler_test.go

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package runtime_test
2+
3+
import (
4+
"io"
5+
"io/ioutil"
6+
"net/http"
7+
"net/http/httptest"
8+
"testing"
9+
10+
"github.com/golang/protobuf/proto"
11+
pb "github.com/grpc-ecosystem/grpc-gateway/examples/examplepb"
12+
"github.com/grpc-ecosystem/grpc-gateway/runtime"
13+
"golang.org/x/net/context"
14+
)
15+
16+
func TestForwardResponseStream(t *testing.T) {
17+
var (
18+
msgs = []proto.Message{
19+
&pb.SimpleMessage{Id: "One"},
20+
&pb.SimpleMessage{Id: "Two"},
21+
}
22+
23+
ctx = runtime.NewServerMetadataContext(
24+
context.Background(), runtime.ServerMetadata{},
25+
)
26+
mux = runtime.NewServeMux()
27+
marshaler = &runtime.JSONPb{}
28+
req = httptest.NewRequest("GET", "http://example.com/foo", nil)
29+
resp = httptest.NewRecorder()
30+
count = 0
31+
recv = func() (proto.Message, error) {
32+
if count >= len(msgs) {
33+
return nil, io.EOF
34+
}
35+
count++
36+
return msgs[count-1], nil
37+
}
38+
)
39+
40+
runtime.ForwardResponseStream(ctx, mux, marshaler, resp, req, recv)
41+
42+
w := resp.Result()
43+
if w.StatusCode != http.StatusOK {
44+
t.Errorf(" got %d want %d", w.StatusCode, http.StatusOK)
45+
}
46+
if h := w.Header.Get("Transfer-Encoding"); h != "chunked" {
47+
t.Errorf("ForwardResponseStream missing header chunked")
48+
}
49+
body, err := ioutil.ReadAll(w.Body)
50+
if err != nil {
51+
t.Errorf("Failed to read response body with %v", err)
52+
}
53+
w.Body.Close()
54+
55+
var want []byte
56+
for _, msg := range msgs {
57+
b, err := marshaler.Marshal(map[string]proto.Message{"result": msg})
58+
if err != nil {
59+
t.Errorf("marshaler.Marshal() failed %v", err)
60+
}
61+
want = append(want, b...)
62+
}
63+
64+
if string(body) != string(want) {
65+
t.Errorf("ForwardResponseStream() = \"%s\" want \"%s\"", body, want)
66+
}
67+
}

0 commit comments

Comments
 (0)