Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
runtime: fix chunk encoding
Browse files Browse the repository at this point in the history
emcfarlane committed Oct 29, 2017

Verified

This commit was signed with the committer’s verified signature.
Vlatombe Vincent Latombe
1 parent b2423da commit 51194e1
Showing 2 changed files with 68 additions and 1 deletion.
2 changes: 1 addition & 1 deletion runtime/handler.go
Original file line number Diff line number Diff line change
@@ -58,7 +58,7 @@ func ForwardResponseStream(ctx context.Context, mux *ServeMux, marshaler Marshal
grpclog.Printf("Failed to marshal response chunk: %v", err)
return
}
if _, err = fmt.Fprintf(w, "%s\n", buf); err != nil {
if _, err = w.Write(buf); err != nil {
grpclog.Printf("Failed to send response chunk: %v", err)
return
}
67 changes: 67 additions & 0 deletions runtime/handler_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package runtime_test

import (
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"

"github.com/golang/protobuf/proto"
pb "github.com/grpc-ecosystem/grpc-gateway/examples/examplepb"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"golang.org/x/net/context"
)

func TestForwardResponseStream(t *testing.T) {
var (
msgs = []proto.Message{
&pb.SimpleMessage{Id: "One"},
&pb.SimpleMessage{Id: "Two"},
}

ctx = runtime.NewServerMetadataContext(
context.Background(), runtime.ServerMetadata{},
)
mux = runtime.NewServeMux()
marshaler = &runtime.JSONPb{}
req = httptest.NewRequest("GET", "http://example.com/foo", nil)
resp = httptest.NewRecorder()
count = 0
recv = func() (proto.Message, error) {
if count >= len(msgs) {
return nil, io.EOF
}
count++
return msgs[count-1], nil
}
)

runtime.ForwardResponseStream(ctx, mux, marshaler, resp, req, recv)

w := resp.Result()
if w.StatusCode != http.StatusOK {
t.Errorf(" got %d want %d", w.StatusCode, http.StatusOK)
}
if h := w.Header.Get("Transfer-Encoding"); h != "chunked" {
t.Errorf("ForwardResponseStream missing header chunked")
}
body, err := ioutil.ReadAll(w.Body)
if err != nil {
t.Errorf("Failed to read response body with %v", err)
}
w.Body.Close()

var want []byte
for _, msg := range msgs {
b, err := marshaler.Marshal(map[string]proto.Message{"result": msg})
if err != nil {
t.Errorf("marshaler.Marshal() failed %v", err)
}
want = append(want, b...)
}

if string(body) != string(want) {
t.Errorf("ForwardResponseStream() = \"%s\" want \"%s\"", body, want)
}
}

0 comments on commit 51194e1

Please sign in to comment.