blob: 525b0338c74715d8e71d41b4bdcd6fca06d646fc [file] [log] [blame]
khenaidooab1f7bd2019-11-14 14:00:27 -05001package runtime
2
3import (
4 "google.golang.org/genproto/googleapis/api/httpbody"
5)
6
7// SetHTTPBodyMarshaler overwrite the default marshaler with the HTTPBodyMarshaler
8func SetHTTPBodyMarshaler(serveMux *ServeMux) {
9 serveMux.marshalers.mimeMap[MIMEWildcard] = &HTTPBodyMarshaler{
10 Marshaler: &JSONPb{OrigName: true},
11 }
12}
13
14// HTTPBodyMarshaler is a Marshaler which supports marshaling of a
15// google.api.HttpBody message as the full response body if it is
16// the actual message used as the response. If not, then this will
17// simply fallback to the Marshaler specified as its default Marshaler.
18type HTTPBodyMarshaler struct {
19 Marshaler
20}
21
khenaidood948f772021-08-11 17:49:24 -040022// ContentType implementation to keep backwards compatibility with marshal interface
khenaidooab1f7bd2019-11-14 14:00:27 -050023func (h *HTTPBodyMarshaler) ContentType() string {
24 return h.ContentTypeFromMessage(nil)
25}
26
27// ContentTypeFromMessage in case v is a google.api.HttpBody message it returns
28// its specified content type otherwise fall back to the default Marshaler.
29func (h *HTTPBodyMarshaler) ContentTypeFromMessage(v interface{}) string {
30 if httpBody, ok := v.(*httpbody.HttpBody); ok {
31 return httpBody.GetContentType()
32 }
33 return h.Marshaler.ContentType()
34}
35
36// Marshal marshals "v" by returning the body bytes if v is a
37// google.api.HttpBody message, otherwise it falls back to the default Marshaler.
38func (h *HTTPBodyMarshaler) Marshal(v interface{}) ([]byte, error) {
39 if httpBody, ok := v.(*httpbody.HttpBody); ok {
40 return httpBody.Data, nil
41 }
42 return h.Marshaler.Marshal(v)
43}