Skip to content

Instantly share code, notes, and snippets.

@yudai
Created July 12, 2017 01:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yudai/fa4d66dd1ae66caf65e8c09eeb2be6b9 to your computer and use it in GitHub Desktop.
Save yudai/fa4d66dd1ae66caf65e8c09eeb2be6b9 to your computer and use it in GitHub Desktop.
// ForwardResponseStream forwards the stream from gRPC server to REST client.
func ForwardResponseStream(ctx context.Context, marshaler Marshaler, w http.ResponseWriter, req *http.Request, recv func() (proto.Message, error), opts ...func(context.Context, http.ResponseWriter, proto.Message) error) {
// f, ok := w.(http.Flusher)
// if !ok {
// grpclog.Printf("Flush not supported in %T", w)
// http.Error(w, "unexpected type of web server", http.StatusInternalServerError)
// return
// }
md, ok := ServerMetadataFromContext(ctx)
if !ok {
grpclog.Printf("Failed to extract ServerMetadata from context")
http.Error(w, "unexpected error", http.StatusInternalServerError)
return
}
handleForwardResponseServerMetadata(w, md)
w.Header().Set("Transfer-Encoding", "chunked")
w.Header().Set("Content-Type", marshaler.ContentType())
if err := handleForwardResponseOptions(ctx, w, nil, opts); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// w.WriteHeader(http.StatusOK)
// f.Flush()
for {
resp, err := recv()
if err == io.EOF {
return
}
if err != nil {
handleForwardResponseStreamError(marshaler, w, err)
return
}
if err := handleForwardResponseOptions(ctx, w, resp, opts); err != nil {
handleForwardResponseStreamError(marshaler, w, err)
return
}
fmt.Println(resp)
// buf, err := marshaler.Marshal(streamChunk(resp, nil))
// if err != nil {
// grpclog.Printf("Failed to marshal response chunk: %v", err)
// return
// }
// if _, err = fmt.Fprintf(w, "%s\n", buf); err != nil {
// grpclog.Printf("Failed to send response chunk: %v", err)
// return
// }
// f.Flush()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment