marshal_httpbodyproto.go 1.5 KB

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