...

Source file src/github.com/emicklei/go-restful/v3/response.go

Documentation: github.com/emicklei/go-restful/v3

     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  		if DefaultResponseMimeType == MIME_ZIP {
   113  			return entityAccessRegistry.accessorAt(MIME_ZIP)
   114  		}
   115  		// Fallback to whatever the route says it can produce.
   116  		// https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
   117  		for _, each := range r.routeProduces {
   118  			if w, ok := entityAccessRegistry.accessorAt(each); ok {
   119  				return w, true
   120  			}
   121  		}
   122  		if trace {
   123  			traceLogger.Printf("no registered EntityReaderWriter found for %s", r.requestAccept)
   124  		}
   125  	}
   126  	return writer, ok
   127  }
   128  
   129  // WriteEntity calls WriteHeaderAndEntity with Http Status OK (200)
   130  func (r *Response) WriteEntity(value interface{}) error {
   131  	return r.WriteHeaderAndEntity(http.StatusOK, value)
   132  }
   133  
   134  // WriteHeaderAndEntity marshals the value using the representation denoted by the Accept Header and the registered EntityWriters.
   135  // If no Accept header is specified (or */*) then respond with the Content-Type as specified by the first in the Route.Produces.
   136  // 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.
   137  // If the value is nil then no response is send except for the Http status. You may want to call WriteHeader(http.StatusNotFound) instead.
   138  // If there is no writer available that can represent the value in the requested MIME type then Http Status NotAcceptable is written.
   139  // Current implementation ignores any q-parameters in the Accept Header.
   140  // Returns an error if the value could not be written on the response.
   141  func (r *Response) WriteHeaderAndEntity(status int, value interface{}) error {
   142  	writer, ok := r.EntityWriter()
   143  	if !ok {
   144  		r.WriteHeader(http.StatusNotAcceptable)
   145  		return nil
   146  	}
   147  	return writer.Write(r, status, value)
   148  }
   149  
   150  // WriteAsXml is a convenience method for writing a value in xml (requires Xml tags on the value)
   151  // It uses the standard encoding/xml package for marshalling the value ; not using a registered EntityReaderWriter.
   152  func (r *Response) WriteAsXml(value interface{}) error {
   153  	return writeXML(r, http.StatusOK, MIME_XML, value)
   154  }
   155  
   156  // WriteHeaderAndXml is a convenience method for writing a status and value in xml (requires Xml tags on the value)
   157  // It uses the standard encoding/xml package for marshalling the value ; not using a registered EntityReaderWriter.
   158  func (r *Response) WriteHeaderAndXml(status int, value interface{}) error {
   159  	return writeXML(r, status, MIME_XML, value)
   160  }
   161  
   162  // WriteAsJson is a convenience method for writing a value in json.
   163  // It uses the standard encoding/json package for marshalling the value ; not using a registered EntityReaderWriter.
   164  func (r *Response) WriteAsJson(value interface{}) error {
   165  	return writeJSON(r, http.StatusOK, MIME_JSON, value)
   166  }
   167  
   168  // WriteJson is a convenience method for writing a value in Json with a given Content-Type.
   169  // It uses the standard encoding/json package for marshalling the value ; not using a registered EntityReaderWriter.
   170  func (r *Response) WriteJson(value interface{}, contentType string) error {
   171  	return writeJSON(r, http.StatusOK, contentType, value)
   172  }
   173  
   174  // WriteHeaderAndJson is a convenience method for writing the status and a value in Json with a given Content-Type.
   175  // It uses the standard encoding/json package for marshalling the value ; not using a registered EntityReaderWriter.
   176  func (r *Response) WriteHeaderAndJson(status int, value interface{}, contentType string) error {
   177  	return writeJSON(r, status, contentType, value)
   178  }
   179  
   180  // WriteError writes the http status and the error string on the response. err can be nil.
   181  // Return an error if writing was not successful.
   182  func (r *Response) WriteError(httpStatus int, err error) (writeErr error) {
   183  	r.err = err
   184  	if err == nil {
   185  		writeErr = r.WriteErrorString(httpStatus, "")
   186  	} else {
   187  		writeErr = r.WriteErrorString(httpStatus, err.Error())
   188  	}
   189  	return writeErr
   190  }
   191  
   192  // WriteServiceError is a convenience method for a responding with a status and a ServiceError
   193  func (r *Response) WriteServiceError(httpStatus int, err ServiceError) error {
   194  	r.err = err
   195  	return r.WriteHeaderAndEntity(httpStatus, err)
   196  }
   197  
   198  // WriteErrorString is a convenience method for an error status with the actual error
   199  func (r *Response) WriteErrorString(httpStatus int, errorReason string) error {
   200  	if r.err == nil {
   201  		// if not called from WriteError
   202  		r.err = errors.New(errorReason)
   203  	}
   204  	r.WriteHeader(httpStatus)
   205  	if _, err := r.Write([]byte(errorReason)); err != nil {
   206  		return err
   207  	}
   208  	return nil
   209  }
   210  
   211  // Flush implements http.Flusher interface, which sends any buffered data to the client.
   212  func (r *Response) Flush() {
   213  	if f, ok := r.ResponseWriter.(http.Flusher); ok {
   214  		f.Flush()
   215  	} else if trace {
   216  		traceLogger.Printf("ResponseWriter %v doesn't support Flush", r)
   217  	}
   218  }
   219  
   220  // WriteHeader is overridden to remember the Status Code that has been written.
   221  // Changes to the Header of the response have no effect after this.
   222  func (r *Response) WriteHeader(httpStatus int) {
   223  	r.statusCode = httpStatus
   224  	r.ResponseWriter.WriteHeader(httpStatus)
   225  }
   226  
   227  // StatusCode returns the code that has been written using WriteHeader.
   228  func (r Response) StatusCode() int {
   229  	if 0 == r.statusCode {
   230  		// no status code has been written yet; assume OK
   231  		return http.StatusOK
   232  	}
   233  	return r.statusCode
   234  }
   235  
   236  // Write writes the data to the connection as part of an HTTP reply.
   237  // Write is part of http.ResponseWriter interface.
   238  func (r *Response) Write(bytes []byte) (int, error) {
   239  	written, err := r.ResponseWriter.Write(bytes)
   240  	r.contentLength += written
   241  	return written, err
   242  }
   243  
   244  // ContentLength returns the number of bytes written for the response content.
   245  // Note that this value is only correct if all data is written through the Response using its Write* methods.
   246  // Data written directly using the underlying http.ResponseWriter is not accounted for.
   247  func (r Response) ContentLength() int {
   248  	return r.contentLength
   249  }
   250  
   251  // CloseNotify is part of http.CloseNotifier interface
   252  func (r Response) CloseNotify() <-chan bool {
   253  	return r.ResponseWriter.(http.CloseNotifier).CloseNotify()
   254  }
   255  
   256  // Error returns the err created by WriteError
   257  func (r Response) Error() error {
   258  	return r.err
   259  }
   260  

View as plain text