| 1 |
package runtime |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"io" |
| 6 |
"net/http" |
| 7 |
"net/textproto" |
| 8 |
|
| 9 |
"github.com/golang/protobuf/proto" |
| 10 |
"github.com/grpc-ecosystem/grpc-gateway/runtime/internal" |
| 11 |
"golang.org/x/net/context" |
| 12 |
"google.golang.org/grpc/codes" |
| 13 |
"google.golang.org/grpc/grpclog" |
| 14 |
"google.golang.org/grpc/status" |
| 15 |
) |
| 16 |
|
| 17 |
// ForwardResponseStream forwards the stream from gRPC server to REST client. |
| 18 |
func ForwardResponseStream(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, req *http.Request, recv func() (proto.Message, error), opts ...func(context.Context, http.ResponseWriter, proto.Message) error) { |
| 19 |
f, ok := w.(http.Flusher) |
| 20 |
if !ok { |
| 21 |
grpclog.Printf("Flush not supported in %T", w) |
| 22 |
http.Error(w, "unexpected type of web server", http.StatusInternalServerError) |
| 23 |
return |
| 24 |
} |
| 25 |
|
| 26 |
md, ok := ServerMetadataFromContext(ctx) |
| 27 |
if !ok { |
| 28 |
grpclog.Printf("Failed to extract ServerMetadata from context") |
| 29 |
http.Error(w, "unexpected error", http.StatusInternalServerError) |
| 30 |
return |
| 31 |
} |
| 32 |
handleForwardResponseServerMetadata(w, mux, md) |
| 33 |
|
| 34 |
w.Header().Set("Transfer-Encoding", "chunked") |
| 35 |
w.Header().Set("Content-Type", marshaler.ContentType()) |
| 36 |
if err := handleForwardResponseOptions(ctx, w, nil, opts); err != nil { |
| 37 |
http.Error(w, err.Error(), http.StatusInternalServerError) |
| 38 |
return |
| 39 |
} |
| 40 |
w.WriteHeader(http.StatusOK) |
| 41 |
f.Flush() |
| 42 |
for { |
| 43 |
resp, err := recv() |
| 44 |
if err == io.EOF { |
| 45 |
return |
| 46 |
} |
| 47 |
if err != nil { |
| 48 |
handleForwardResponseStreamError(marshaler, w, err) |
| 49 |
return |
| 50 |
} |
| 51 |
if err := handleForwardResponseOptions(ctx, w, resp, opts); err != nil { |
| 52 |
handleForwardResponseStreamError(marshaler, w, err) |
| 53 |
return |
| 54 |
} |
| 55 |
|
| 56 |
buf, err := marshaler.Marshal(streamChunk(resp, nil)) |
| 57 |
if err != nil { |
| 58 |
grpclog.Printf("Failed to marshal response chunk: %v", err) |
| 59 |
return |
| 60 |
} |
| 61 |
if _, err = w.Write(buf); err != nil { |
| 62 |
grpclog.Printf("Failed to send response chunk: %v", err) |
| 63 |
return |
| 64 |
} |
| 65 |
f.Flush() |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
func handleForwardResponseServerMetadata(w http.ResponseWriter, mux *ServeMux, md ServerMetadata) { |
| 70 |
for k, vs := range md.HeaderMD { |
| 71 |
if h, ok := mux.outgoingHeaderMatcher(k); ok { |
| 72 |
for _, v := range vs { |
| 73 |
w.Header().Add(h, v) |
| 74 |
} |
| 75 |
} |
| 76 |
} |
| 77 |
} |
| 78 |
|
| 79 |
func handleForwardResponseTrailerHeader(w http.ResponseWriter, md ServerMetadata) { |
| 80 |
for k := range md.TrailerMD { |
| 81 |
tKey := textproto.CanonicalMIMEHeaderKey(fmt.Sprintf("%s%s", MetadataTrailerPrefix, k)) |
| 82 |
w.Header().Add("Trailer", tKey) |
| 83 |
} |
| 84 |
} |
| 85 |
|
| 86 |
func handleForwardResponseTrailer(w http.ResponseWriter, md ServerMetadata) { |
| 87 |
for k, vs := range md.TrailerMD { |
| 88 |
tKey := fmt.Sprintf("%s%s", MetadataTrailerPrefix, k) |
| 89 |
for _, v := range vs { |
| 90 |
w.Header().Add(tKey, v) |
| 91 |
} |
| 92 |
} |
| 93 |
} |
| 94 |
|
| 95 |
// ForwardResponseMessage forwards the message "resp" from gRPC server to REST client. |
| 96 |
func ForwardResponseMessage(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, req *http.Request, resp proto.Message, opts ...func(context.Context, http.ResponseWriter, proto.Message) error) { |
| 97 |
md, ok := ServerMetadataFromContext(ctx) |
| 98 |
if !ok { |
| 99 |
grpclog.Printf("Failed to extract ServerMetadata from context") |
| 100 |
} |
| 101 |
|
| 102 |
handleForwardResponseServerMetadata(w, mux, md) |
| 103 |
handleForwardResponseTrailerHeader(w, md) |
| 104 |
w.Header().Set("Content-Type", marshaler.ContentType()) |
| 105 |
if err := handleForwardResponseOptions(ctx, w, resp, opts); err != nil { |
| 106 |
HTTPError(ctx, mux, marshaler, w, req, err) |
| 107 |
return |
| 108 |
} |
| 109 |
|
| 110 |
buf, err := marshaler.Marshal(resp) |
| 111 |
if err != nil { |
| 112 |
grpclog.Printf("Marshal error: %v", err) |
| 113 |
HTTPError(ctx, mux, marshaler, w, req, err) |
| 114 |
return |
| 115 |
} |
| 116 |
|
| 117 |
if _, err = w.Write(buf); err != nil { |
| 118 |
grpclog.Printf("Failed to write response: %v", err) |
| 119 |
} |
| 120 |
|
| 121 |
handleForwardResponseTrailer(w, md) |
| 122 |
} |
| 123 |
|
| 124 |
func handleForwardResponseOptions(ctx context.Context, w http.ResponseWriter, resp proto.Message, opts []func(context.Context, http.ResponseWriter, proto.Message) error) error { |
| 125 |
if len(opts) == 0 { |
| 126 |
return nil |
| 127 |
} |
| 128 |
for _, opt := range opts { |
| 129 |
if err := opt(ctx, w, resp); err != nil { |
| 130 |
grpclog.Printf("Error handling ForwardResponseOptions: %v", err) |
| 131 |
return err |
| 132 |
} |
| 133 |
} |
| 134 |
return nil |
| 135 |
} |
| 136 |
|
| 137 |
func handleForwardResponseStreamError(marshaler Marshaler, w http.ResponseWriter, err error) { |
| 138 |
buf, merr := marshaler.Marshal(streamChunk(nil, err)) |
| 139 |
if merr != nil { |
| 140 |
grpclog.Printf("Failed to marshal an error: %v", merr) |
| 141 |
return |
| 142 |
} |
| 143 |
if _, werr := fmt.Fprintf(w, "%s\n", buf); werr != nil { |
| 144 |
grpclog.Printf("Failed to notify error to client: %v", werr) |
| 145 |
return |
| 146 |
} |
| 147 |
} |
| 148 |
|
| 149 |
func streamChunk(result proto.Message, err error) map[string]proto.Message { |
| 150 |
if err != nil { |
| 151 |
grpcCode := codes.Unknown |
| 152 |
if s, ok := status.FromError(err); ok { |
| 153 |
grpcCode = s.Code() |
| 154 |
} |
| 155 |
httpCode := HTTPStatusFromCode(grpcCode) |
| 156 |
return map[string]proto.Message{ |
| 157 |
"error": &internal.StreamError{ |
| 158 |
GrpcCode: int32(grpcCode), |
| 159 |
HttpCode: int32(httpCode), |
| 160 |
Message: err.Error(), |
| 161 |
HttpStatus: http.StatusText(httpCode), |
| 162 |
}, |
| 163 |
} |
| 164 |
} |
| 165 |
if result == nil { |
| 166 |
return streamChunk(nil, fmt.Errorf("empty response")) |
| 167 |
} |
| 168 |
return map[string]proto.Message{"result": result} |
| 169 |
} |