blob: f55285b5d6ca8da94efd5490fd85adbaf981f761 [file] [log] [blame]
Don Newton379ae252019-04-01 12:17:06 -04001package 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
22// ContentType implementation to keep backwards compatability with marshal interface
23func (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}