response.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. package restful
  2. // Copyright 2013 Ernest Micklei. All rights reserved.
  3. // Use of this source code is governed by a license
  4. // that can be found in the LICENSE file.
  5. import (
  6. "errors"
  7. "net/http"
  8. )
  9. // DefaultResponseMimeType is DEPRECATED, use DefaultResponseContentType(mime)
  10. var DefaultResponseMimeType string
  11. //PrettyPrintResponses controls the indentation feature of XML and JSON serialization
  12. var PrettyPrintResponses = true
  13. // Response is a wrapper on the actual http ResponseWriter
  14. // It provides several convenience methods to prepare and write response content.
  15. type Response struct {
  16. http.ResponseWriter
  17. requestAccept string // mime-type what the Http Request says it wants to receive
  18. routeProduces []string // mime-types what the Route says it can produce
  19. statusCode int // HTTP status code that has been written explicity (if zero then net/http has written 200)
  20. contentLength int // number of bytes written for the response body
  21. prettyPrint bool // controls the indentation feature of XML and JSON serialization. It is initialized using var PrettyPrintResponses.
  22. err error // err property is kept when WriteError is called
  23. }
  24. // NewResponse creates a new response based on a http ResponseWriter.
  25. func NewResponse(httpWriter http.ResponseWriter) *Response {
  26. return &Response{httpWriter, "", []string{}, http.StatusOK, 0, PrettyPrintResponses, nil} // empty content-types
  27. }
  28. // DefaultResponseContentType set a default.
  29. // If Accept header matching fails, fall back to this type.
  30. // Valid values are restful.MIME_JSON and restful.MIME_XML
  31. // Example:
  32. // restful.DefaultResponseContentType(restful.MIME_JSON)
  33. func DefaultResponseContentType(mime string) {
  34. DefaultResponseMimeType = mime
  35. }
  36. // InternalServerError writes the StatusInternalServerError header.
  37. // DEPRECATED, use WriteErrorString(http.StatusInternalServerError,reason)
  38. func (r Response) InternalServerError() Response {
  39. r.WriteHeader(http.StatusInternalServerError)
  40. return r
  41. }
  42. // PrettyPrint changes whether this response must produce pretty (line-by-line, indented) JSON or XML output.
  43. func (r *Response) PrettyPrint(bePretty bool) {
  44. r.prettyPrint = bePretty
  45. }
  46. // AddHeader is a shortcut for .Header().Add(header,value)
  47. func (r Response) AddHeader(header string, value string) Response {
  48. r.Header().Add(header, value)
  49. return r
  50. }
  51. // SetRequestAccepts tells the response what Mime-type(s) the HTTP request said it wants to accept. Exposed for testing.
  52. func (r *Response) SetRequestAccepts(mime string) {
  53. r.requestAccept = mime
  54. }
  55. // EntityWriter returns the registered EntityWriter that the entity (requested resource)
  56. // can write according to what the request wants (Accept) and what the Route can produce or what the restful defaults say.
  57. // If called before WriteEntity and WriteHeader then a false return value can be used to write a 406: Not Acceptable.
  58. func (r *Response) EntityWriter() (EntityReaderWriter, bool) {
  59. sorted := sortedMimes(r.requestAccept)
  60. for _, eachAccept := range sorted {
  61. for _, eachProduce := range r.routeProduces {
  62. if eachProduce == eachAccept.media {
  63. if w, ok := entityAccessRegistry.accessorAt(eachAccept.media); ok {
  64. return w, true
  65. }
  66. }
  67. }
  68. if eachAccept.media == "*/*" {
  69. for _, each := range r.routeProduces {
  70. if w, ok := entityAccessRegistry.accessorAt(each); ok {
  71. return w, true
  72. }
  73. }
  74. }
  75. }
  76. // if requestAccept is empty
  77. writer, ok := entityAccessRegistry.accessorAt(r.requestAccept)
  78. if !ok {
  79. // if not registered then fallback to the defaults (if set)
  80. if DefaultResponseMimeType == MIME_JSON {
  81. return entityAccessRegistry.accessorAt(MIME_JSON)
  82. }
  83. if DefaultResponseMimeType == MIME_XML {
  84. return entityAccessRegistry.accessorAt(MIME_XML)
  85. }
  86. // Fallback to whatever the route says it can produce.
  87. // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
  88. for _, each := range r.routeProduces {
  89. if w, ok := entityAccessRegistry.accessorAt(each); ok {
  90. return w, true
  91. }
  92. }
  93. if trace {
  94. traceLogger.Printf("no registered EntityReaderWriter found for %s", r.requestAccept)
  95. }
  96. }
  97. return writer, ok
  98. }
  99. // WriteEntity calls WriteHeaderAndEntity with Http Status OK (200)
  100. func (r *Response) WriteEntity(value interface{}) error {
  101. return r.WriteHeaderAndEntity(http.StatusOK, value)
  102. }
  103. // WriteHeaderAndEntity marshals the value using the representation denoted by the Accept Header and the registered EntityWriters.
  104. // If no Accept header is specified (or */*) then respond with the Content-Type as specified by the first in the Route.Produces.
  105. // If an Accept header is specified then respond with the Content-Type as specified by the first in the Route.Produces that is matched with the Accept header.
  106. // If the value is nil then no response is send except for the Http status. You may want to call WriteHeader(http.StatusNotFound) instead.
  107. // If there is no writer available that can represent the value in the requested MIME type then Http Status NotAcceptable is written.
  108. // Current implementation ignores any q-parameters in the Accept Header.
  109. // Returns an error if the value could not be written on the response.
  110. func (r *Response) WriteHeaderAndEntity(status int, value interface{}) error {
  111. writer, ok := r.EntityWriter()
  112. if !ok {
  113. r.WriteHeader(http.StatusNotAcceptable)
  114. return nil
  115. }
  116. return writer.Write(r, status, value)
  117. }
  118. // WriteAsXml is a convenience method for writing a value in xml (requires Xml tags on the value)
  119. // It uses the standard encoding/xml package for marshalling the value ; not using a registered EntityReaderWriter.
  120. func (r *Response) WriteAsXml(value interface{}) error {
  121. return writeXML(r, http.StatusOK, MIME_XML, value)
  122. }
  123. // WriteHeaderAndXml is a convenience method for writing a status and value in xml (requires Xml tags on the value)
  124. // It uses the standard encoding/xml package for marshalling the value ; not using a registered EntityReaderWriter.
  125. func (r *Response) WriteHeaderAndXml(status int, value interface{}) error {
  126. return writeXML(r, status, MIME_XML, value)
  127. }
  128. // WriteAsJson is a convenience method for writing a value in json.
  129. // It uses the standard encoding/json package for marshalling the value ; not using a registered EntityReaderWriter.
  130. func (r *Response) WriteAsJson(value interface{}) error {
  131. return writeJSON(r, http.StatusOK, MIME_JSON, value)
  132. }
  133. // WriteJson is a convenience method for writing a value in Json with a given Content-Type.
  134. // It uses the standard encoding/json package for marshalling the value ; not using a registered EntityReaderWriter.
  135. func (r *Response) WriteJson(value interface{}, contentType string) error {
  136. return writeJSON(r, http.StatusOK, contentType, value)
  137. }
  138. // WriteHeaderAndJson is a convenience method for writing the status and a value in Json with a given Content-Type.
  139. // It uses the standard encoding/json package for marshalling the value ; not using a registered EntityReaderWriter.
  140. func (r *Response) WriteHeaderAndJson(status int, value interface{}, contentType string) error {
  141. return writeJSON(r, status, contentType, value)
  142. }
  143. // WriteError write the http status and the error string on the response.
  144. func (r *Response) WriteError(httpStatus int, err error) error {
  145. r.err = err
  146. return r.WriteErrorString(httpStatus, err.Error())
  147. }
  148. // WriteServiceError is a convenience method for a responding with a status and a ServiceError
  149. func (r *Response) WriteServiceError(httpStatus int, err ServiceError) error {
  150. r.err = err
  151. return r.WriteHeaderAndEntity(httpStatus, err)
  152. }
  153. // WriteErrorString is a convenience method for an error status with the actual error
  154. func (r *Response) WriteErrorString(httpStatus int, errorReason string) error {
  155. if r.err == nil {
  156. // if not called from WriteError
  157. r.err = errors.New(errorReason)
  158. }
  159. r.WriteHeader(httpStatus)
  160. if _, err := r.Write([]byte(errorReason)); err != nil {
  161. return err
  162. }
  163. return nil
  164. }
  165. // Flush implements http.Flusher interface, which sends any buffered data to the client.
  166. func (r *Response) Flush() {
  167. if f, ok := r.ResponseWriter.(http.Flusher); ok {
  168. f.Flush()
  169. } else if trace {
  170. traceLogger.Printf("ResponseWriter %v doesn't support Flush", r)
  171. }
  172. }
  173. // WriteHeader is overridden to remember the Status Code that has been written.
  174. // Changes to the Header of the response have no effect after this.
  175. func (r *Response) WriteHeader(httpStatus int) {
  176. r.statusCode = httpStatus
  177. r.ResponseWriter.WriteHeader(httpStatus)
  178. }
  179. // StatusCode returns the code that has been written using WriteHeader.
  180. func (r Response) StatusCode() int {
  181. if 0 == r.statusCode {
  182. // no status code has been written yet; assume OK
  183. return http.StatusOK
  184. }
  185. return r.statusCode
  186. }
  187. // Write writes the data to the connection as part of an HTTP reply.
  188. // Write is part of http.ResponseWriter interface.
  189. func (r *Response) Write(bytes []byte) (int, error) {
  190. written, err := r.ResponseWriter.Write(bytes)
  191. r.contentLength += written
  192. return written, err
  193. }
  194. // ContentLength returns the number of bytes written for the response content.
  195. // Note that this value is only correct if all data is written through the Response using its Write* methods.
  196. // Data written directly using the underlying http.ResponseWriter is not accounted for.
  197. func (r Response) ContentLength() int {
  198. return r.contentLength
  199. }
  200. // CloseNotify is part of http.CloseNotifier interface
  201. func (r Response) CloseNotify() <-chan bool {
  202. return r.ResponseWriter.(http.CloseNotifier).CloseNotify()
  203. }
  204. // Error returns the err created by WriteError
  205. func (r Response) Error() error {
  206. return r.err
  207. }