response.go 9.3 KB

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