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