drogon
C++14/17-based HTTP application framework
Loading...
Searching...
No Matches
drogon::HttpResponse Class Referenceabstract

Public Types

using SendfileRange = std::pair<size_t, size_t>
 Returns the range of the file response as a pair of size_t (offset, length). Length of 0 means the entire file is sent. Behavior of this function is undefined if the response is not a file response.

Public Member Functions

template<typename T>
 operator T () const
 This template enables automatic type conversion. For using this template, user must specialize the fromResponse template. For example a shared_ptr<Json::Value> specialization version is available above, so we can use the following code to get a json object:
template<typename T>
as () const
 This template enables explicit type conversion, see the above template.
virtual HttpStatusCode statusCode () const =0
 Get the status code such as 200, 404.
HttpStatusCode getStatusCode () const
virtual void setStatusCode (HttpStatusCode code)=0
 Set the status code of the response.
void setCustomStatusCode (int code, std::string_view message=std::string_view{})
virtual void setAllowCompression (bool allow)=0
 Set whether the response should be compress.
virtual bool allowCompression () const =0
 Get whether the response allow compression.
virtual const trantor::Date & creationDate () const =0
 Get the creation timestamp of the response.
const trantor::Date & getCreationDate () const
virtual void setVersion (const Version v)=0
 Set the http version, http1.0 or http1.1.
virtual void setCloseConnection (bool on)=0
 Set if close the connection after the request is sent.
virtual bool ifCloseConnection () const =0
 Get the status set by the setCloseConnection() method.
virtual void setContentTypeCode (ContentType type)=0
void setContentTypeString (const std::string_view &typeString)
void setContentTypeCodeAndCustomString (ContentType type, const std::string_view &typeString)
template<int N>
void setContentTypeCodeAndCustomString (ContentType type, const char(&typeString)[N])
virtual ContentType contentType () const =0
 Get the response content type.
ContentType getContentType () const
virtual const std::string & getHeader (std::string key) const =0
 Get the header string identified by the key parameter.
virtual void removeHeader (std::string key)=0
 Remove the header identified by the key parameter.
virtual const SafeStringMap< std::string > & headers () const =0
 Get all headers of the response.
const SafeStringMap< std::string > & getHeaders () const
 Get all headers of the response.
virtual void addHeader (std::string field, const std::string &value)=0
 Set the header string identified by the field parameter.
virtual void addHeader (std::string field, std::string &&value)=0
virtual void addCookie (const std::string &key, const std::string &value)=0
 Add a cookie.
virtual void addCookie (const Cookie &cookie)=0
 Add a cookie.
virtual void addCookie (Cookie &&cookie)=0
virtual const CookiegetCookie (const std::string &key) const =0
virtual const SafeStringMap< Cookie > & cookies () const =0
 Get all cookies.
const SafeStringMap< Cookie > & getCookies () const
 Get all cookies.
virtual void removeCookie (const std::string &key)=0
 Remove the cookie identified by the key parameter.
virtual void setBody (const std::string &body)=0
 Set the response body(content).
virtual void setBody (std::string &&body)=0
 Set the response body(content).
template<int N>
void setBody (const char(&body)[N])
 Set the response body(content).
std::string_view body () const
 Get the response body.
std::string_view getBody () const
 Get the response body.
virtual const char * versionString () const =0
const char * getVersionString () const
virtual Version version () const =0
 Return the enum type version of the response.
Version getVersion () const
 Return the enum type version of the response.
virtual void clear ()=0
 Reset the response object to its initial state.
virtual void setExpiredTime (ssize_t expiredTime)=0
virtual ssize_t expiredTime () const =0
 Get the expiration time of the response.
ssize_t getExpiredTime () const
virtual const std::shared_ptr< Json::Value > & jsonObject () const =0
const std::shared_ptr< Json::Value > & getJsonObject () const
virtual const std::string & getJsonError () const =0
 Get the error message of parsing the JSON body received from peer. This method usually is called after getting a empty shared_ptr object by the getJsonObject() method.
virtual void setPassThrough (bool flag)=0
 Set the response object to the pass-through mode or not. It's not by default when a new response object is created. In pass-through mode, no additional headers (including server, date, content-type and content-length, etc.) are added to the response. This mode is useful for some applications such as a proxy.
virtual const trantor::CertificatePtr & peerCertificate () const =0
 Get the certificate of the peer, if any.
const trantor::CertificatePtr & getPeerCertificate () const
void addCorsHeaders (const HttpRequestPtr &request, const std::set< std::string_view > &exposedHeaders={}, const std::optional< bool > &allowCredentials={})
 Add CORS headers to a response.
virtual const std::string & sendfileName () const =0
 If the response is a file response (i.e. created by newFileResponse) returns the path on the filesystem. Otherwise a empty string.
virtual const SendfileRangesendfileRange () const =0
virtual const std::function< std::size_t(char *, std::size_t)> & streamCallback () const =0
 If the response is a stream response (i.e. created by newStreamResponse) returns the callback function. Otherwise a null function.
virtual const std::function< void(ResponseStreamPtr)> & asyncStreamCallback () const =0
 If the response is a async stream response (i.e. created by asyncStreamCallback) returns the stream ptr.
virtual std::string contentTypeString () const =0
 Returns the content type associated with the response.

Static Public Member Functions

static HttpResponsePtr newHttpResponse ()
static HttpResponsePtr newHttpResponse (HttpStatusCode code, ContentType type)
 Create a response with a status code and a content type.
static HttpResponsePtr newNotFoundResponse (const HttpRequestPtr &req=HttpRequestPtr())
 Create a response which returns a 404 page.
static HttpResponsePtr newHttpJsonResponse (const Json::Value &data)
static HttpResponsePtr newHttpJsonResponse (Json::Value &&data)
static HttpResponsePtr newHttpViewResponse (const std::string &viewName, const HttpViewData &data=HttpViewData(), const HttpRequestPtr &req=HttpRequestPtr())
static HttpResponsePtr newRedirectionResponse (const std::string &location, HttpStatusCode status=k302Found)
static HttpResponsePtr newFileResponse (const std::string &fullPath, const std::string &attachmentFileName="", ContentType type=CT_NONE, const std::string &typeString="", const HttpRequestPtr &req=HttpRequestPtr())
 Create a response that returns a file to the client.
static HttpResponsePtr newFileResponse (const std::string &fullPath, size_t offset, size_t length, bool setContentRange=true, const std::string &attachmentFileName="", ContentType type=CT_NONE, const std::string &typeString="", const HttpRequestPtr &req=HttpRequestPtr())
 Create a response that returns part of a file to the client.
static HttpResponsePtr newFileResponse (const unsigned char *pBuffer, size_t bufferLength, const std::string &attachmentFileName="", ContentType type=CT_NONE, const std::string &typeString="")
static HttpResponsePtr newStreamResponse (const std::function< std::size_t(char *, std::size_t)> &callback, const std::string &attachmentFileName="", ContentType type=CT_NONE, const std::string &typeString="", const HttpRequestPtr &req=HttpRequestPtr())
static HttpResponsePtr newAsyncStreamResponse (const std::function< void(ResponseStreamPtr)> &callback, bool disableKickoffTimeout=false)
template<typename T>
static HttpResponsePtr newCustomHttpResponse (T &&obj)
 Create a custom HTTP response object. For using this template, users must specialize the toResponse template.
static HttpResponsePtr newOptionsResponse (const HttpRequestPtr &request, const std::function< bool(std::string_view)> &originValidator=nullptr, bool allowNullOrigin=false, bool allowCredentials=false, bool allowPNA=true, std::optional< unsigned int > maxAgeSeconds={}, const std::optional< std::set< std::string_view > > &allowedHeaders=std::nullopt)
 Create an OPTIONS or CORS pre-flight response.
static HttpResponsePtr newOptionsResponse (const HttpRequestPtr &request, const std::set< std::string_view > &allowedHeaders, const std::function< bool(std::string_view)> &originValidator=nullptr, bool allowNullOrigin=false, bool allowCredentials=false, bool allowPNA=true, std::optional< unsigned int > maxAgeSeconds={})
 Create an OPTIONS or CORS pre-flight response.

Member Function Documentation

◆ addCorsHeaders()

void drogon::HttpResponse::addCorsHeaders ( const HttpRequestPtr & request,
const std::set< std::string_view > & exposedHeaders = {},
const std::optional< bool > & allowCredentials = {} )

Add CORS headers to a response.

Adds the CORS headers to a response for a normal request (a CORS request but not a CORS preflight request):

  • does nothing if it's an OPTIONS request, or
  • if it's not a CORS request, or
  • if it's a CORS preflight request Else:
  • adds Access-Control-Allow-Origin (if not yet present)
  • adds Origin to the Vary header,
  • sets or clears Access-Control-Allow-Credentials (if allowCredentials is set)
  • completes Access-Control-Expose-Headers
    Parameters
    [in]requestDrogon request (to get Origin)
    [in]allowCredentialsIf set and true, adds the "Access-Control-Allow-Credentials: true header"
    If set and false, removes the "Access-Control-Allow-Credentials" header
    If not set, leaves the "Access-Control-Allow-Credentials" header untouched
    MUST MATCH THE newOptionsResponse() PRE-FLIGHT RESPONSE VALUE
    [in]exposedHeadersSet of exposed headers (for Access-Control-Expose-Headers header)
    These are the headers allowed to be exposed to javascript by the remote browser
    Note: they are APPENDED to any already present in the response, they are not REPLACED.
    This allows to complete them in the controller path handler.
    If you want to REPLACE them, remove the header before calling this function.
    Note
    may be use both in the controller path handler and in a pre-sending advice

◆ addHeader()

virtual void drogon::HttpResponse::addHeader ( std::string field,
const std::string & value )
pure virtual

Set the header string identified by the field parameter.

Parameters
fieldThe field parameter is transformed to lower case before storing.
valueThe value of the header.

◆ contentType()

virtual ContentType drogon::HttpResponse::contentType ( ) const
pure virtual

Get the response content type.

Set the response content type and the character set. virtual void setContentTypeCodeAndCharacterSet(ContentType type, const std::string &charSet = "utf-8") = 0;

◆ getCookie()

virtual const Cookie & drogon::HttpResponse::getCookie ( const std::string & key) const
pure virtual

Get the cookie identified by the key parameter. If there is no the cookie, the empty cookie is returned.

◆ getHeader()

virtual const std::string & drogon::HttpResponse::getHeader ( std::string key) const
pure virtual

Get the header string identified by the key parameter.

Note
If there is no the header, a empty string is returned. The key is case insensitive

◆ getJsonError()

virtual const std::string & drogon::HttpResponse::getJsonError ( ) const
pure virtual

Get the error message of parsing the JSON body received from peer. This method usually is called after getting a empty shared_ptr object by the getJsonObject() method.

Returns
const std::string& The error message. An empty string is returned when no error occurs.

◆ jsonObject()

virtual const std::shared_ptr< Json::Value > & drogon::HttpResponse::jsonObject ( ) const
pure virtual

Get the json object from the server response. If the response is not in json format, then a empty shared_ptr is returned.

◆ newAsyncStreamResponse()

HttpResponsePtr drogon::HttpResponse::newAsyncStreamResponse ( const std::function< void(ResponseStreamPtr)> & callback,
bool disableKickoffTimeout = false )
static

Create a response that allows sending asynchronous data from a callback function

Note
Async streams are always sent with Transfer-Encoding: chunked.
Parameters
callbackfunction that receives the asynchronous HTTP stream. You may call the stream->send() method to transmit new data. The send method will return true as long as the stream is still open. Once you have finished sending data, or the stream->send() function returned false, you should call stream->close() to gracefully close the chunked transfer.
disableKickoffTimeoutset this to true to disable trantors default kickoff timeout. This is useful if you need long running asynchronous streams.

◆ newFileResponse() [1/3]

HttpResponsePtr drogon::HttpResponse::newFileResponse ( const std::string & fullPath,
const std::string & attachmentFileName = "",
ContentType type = CT_NONE,
const std::string & typeString = "",
const HttpRequestPtr & req = HttpRequestPtr() )
static

Create a response that returns a file to the client.

Parameters
fullPathis the full path to the file.
attachmentFileNameif the parameter is not empty, the browser does not open the file, but saves it as an attachment.
typethe content type code. If the parameter is CT_NONE, the content type is set by drogon based on the file extension and typeString. Set it to CT_CUSTOM when no drogon internal content type matches.
typeStringthe MIME string of the content type.

◆ newFileResponse() [2/3]

HttpResponsePtr drogon::HttpResponse::newFileResponse ( const std::string & fullPath,
size_t offset,
size_t length,
bool setContentRange = true,
const std::string & attachmentFileName = "",
ContentType type = CT_NONE,
const std::string & typeString = "",
const HttpRequestPtr & req = HttpRequestPtr() )
static

Create a response that returns part of a file to the client.

If offset and length can not be satisfied, statusCode will be set to k416RequestedRangeNotSatisfiable, and nothing else will be modified.

Parameters
fullPathis the full path to the file.
offsetis the offset to begin sending, in bytes.
lengthis the total length to send, in bytes. In particular, length = 0 means send all content from offset till end of file.
setContentRangewhether set 'Content-Range' header automatically.
attachmentFileNameif the parameter is not empty, the browser does not open the file, but saves it as an attachment.
typethe content type code. If the parameter is CT_NONE, the content type is set by drogon based on the file extension and typeString. Set it to CT_CUSTOM when no drogon internal content type matches.
typeStringthe MIME string of the content type.

◆ newFileResponse() [3/3]

HttpResponsePtr drogon::HttpResponse::newFileResponse ( const unsigned char * pBuffer,
size_t bufferLength,
const std::string & attachmentFileName = "",
ContentType type = CT_NONE,
const std::string & typeString = "" )
static

Create a response that returns a file to the client from buffer in memory/stack

Parameters
pBufferis a uint 8 bit flat buffer for object/files in memory
bufferLengthis the length of the expected buffer
attachmentFileNameif the parameter is not empty, the browser does not open the file, but saves it as an attachment.
typethe content type code. If the parameter is CT_NONE, the content type is set by drogon based on the file extension and typeString. Set it to CT_CUSTOM when no drogon internal content type matches.
typeStringthe MIME string of the content type.

◆ newHttpJsonResponse() [1/2]

HttpResponsePtr drogon::HttpResponse::newHttpJsonResponse ( const Json::Value & data)
static

Create a response which returns a json object. Its content-type is set to application/json.

◆ newHttpJsonResponse() [2/2]

HttpResponsePtr drogon::HttpResponse::newHttpJsonResponse ( Json::Value && data)
static

Create a response which returns a json object. Its content-type is set to application/json.

◆ newHttpResponse()

HttpResponsePtr drogon::HttpResponse::newHttpResponse ( )
static

Create a normal response with a status code of 200ok and a content type of text/html.

◆ newHttpViewResponse()

HttpResponsePtr drogon::HttpResponse::newHttpViewResponse ( const std::string & viewName,
const HttpViewData & data = HttpViewData(),
const HttpRequestPtr & req = HttpRequestPtr() )
static

Create a response that returns a page rendered by a view named viewName.

Parameters
viewNameThe name of the view
datais the data displayed on the page.
Note
For more details, see the wiki pages, the "View" section.

◆ newOptionsResponse() [1/2]

HttpResponsePtr drogon::HttpResponse::newOptionsResponse ( const HttpRequestPtr & request,
const std::function< bool(std::string_view)> & originValidator = nullptr,
bool allowNullOrigin = false,
bool allowCredentials = false,
bool allowPNA = true,
std::optional< unsigned int > maxAgeSeconds = {},
const std::optional< std::set< std::string_view > > & allowedHeaders = std::nullopt )
static

Create an OPTIONS or CORS pre-flight response.

If the request is not an OPTIONS request, returns a NULL response
If it is a generic OPTIONS request, returns a 204 No Content response with the Allow header
If it is a CORS pre-flight request, returns a 204 No Content response with the CORS headers set

Other status codes for CORS pre-flight answers:

  • 400 Bad Request: if the request is malformed (missing required headers)
  • 403 Forbidden: if the Origin is not allowed + reason in a X-Cors-Error header
  • 403 Forbidden: if one of the headers in Access-Control-Request-Headers is not allowed + reason in a X-Cors-Error header
  • 405 Method Not Allowed: if the requested method is not allowed
    Note
    CORS is a browser-side security mechanism.
    Do not rely on Origin for authentication/authorization: non-browser clients can spoof or omit it.
    Enforce access control independently.
    Parameters
    [in]requestDrogon (OPTIONS) request
    [in]allowedHeadersSet of allowed headers (for Access-Control-Allow-Headers header)
    (headers allowed by the controller path handler)
    [in]originValidatorFunction to validate the Origin header value (allow the origin or not)
    If allowCredentials is true, originValidator SHOULD enforce a strict allowlist
    [in]allowNullOriginShould be true to accept the "Origin: null" header
    (set for local file:// pages, sandboxed iframes, opaque origins, data: URIs)
    [in]allowCredentialsShould be true to add the header "Access-Control-Allow-Credentials: true" (controls whether the browser may include credentials such as cookies, HTTP auth, or client certificates)
    Note: Authorization (bearer) is not a credential header; allow it via allowedHeaders when needed
    [in]allowPNAShould be true to accept the header "Access-Control-Request-Private-Network" (when a page from a less private address space is trying to reach a more private one, like internet -> intranet)
    Note: specific to Chromium & derivatives (Edge, Opera, Brave, ...), not in Firefox or Safari
    [in]maxAgeSecondsIf set, adds the "Access-Control-Max-Age" header with the given value (in seconds, how long the results of a preflight request can be cached by the navigator)
    Returns
    the OPTIONS or CORS pre-flight response, or a null pointer if the request is not an OPTIONS request

◆ newOptionsResponse() [2/2]

HttpResponsePtr drogon::HttpResponse::newOptionsResponse ( const HttpRequestPtr & request,
const std::set< std::string_view > & allowedHeaders,
const std::function< bool(std::string_view)> & originValidator = nullptr,
bool allowNullOrigin = false,
bool allowCredentials = false,
bool allowPNA = true,
std::optional< unsigned int > maxAgeSeconds = {} )
inlinestatic

Create an OPTIONS or CORS pre-flight response.

If the request is not an OPTIONS request, returns a NULL response
If it is a generic OPTIONS request, returns a 204 No Content response with the Allow header
If it is a CORS pre-flight request, returns a 204 No Content response with the CORS headers set

Other status codes for CORS pre-flight answers:

  • 400 Bad Request: if the request is malformed (missing required headers)
  • 403 Forbidden: if the Origin is not allowed + reason in a X-Cors-Error header
  • 403 Forbidden: if one of the headers in Access-Control-Request-Headers is not allowed + reason in a X-Cors-Error header
  • 405 Method Not Allowed: if the requested method is not allowed
    Note
    CORS is a browser-side security mechanism.
    Do not rely on Origin for authentication/authorization: non-browser clients can spoof or omit it.
    Enforce access control independently.
    Parameters
    [in]requestDrogon (OPTIONS) request
    [in]allowedHeadersSet of allowed headers (for Access-Control-Allow-Headers header)
    (headers allowed by the controller path handler)
    [in]originValidatorFunction to validate the Origin header value (allow the origin or not)
    If allowCredentials is true, originValidator SHOULD enforce a strict allowlist
    [in]allowNullOriginShould be true to accept the "Origin: null" header
    (set for local file:// pages, sandboxed iframes, opaque origins, data: URIs)
    [in]allowCredentialsShould be true to add the header "Access-Control-Allow-Credentials: true" (controls whether the browser may include credentials such as cookies, HTTP auth, or client certificates)
    Note: Authorization (bearer) is not a credential header; allow it via allowedHeaders when needed
    [in]allowPNAShould be true to accept the header "Access-Control-Request-Private-Network" (when a page from a less private address space is trying to reach a more private one, like internet -> intranet)
    Note: specific to Chromium & derivatives (Edge, Opera, Brave, ...), not in Firefox or Safari
    [in]maxAgeSecondsIf set, adds the "Access-Control-Max-Age" header with the given value (in seconds, how long the results of a preflight request can be cached by the navigator)
    Returns
    the OPTIONS or CORS pre-flight response, or a null pointer if the request is not an OPTIONS request
    Remarks
    Helper when specifying the allowed headers, when other parameters may be default, to avoid having to specify them all

◆ newRedirectionResponse()

HttpResponsePtr drogon::HttpResponse::newRedirectionResponse ( const std::string & location,
HttpStatusCode status = k302Found )
static

Create a response that returns a redirection page, redirecting to another page located in the location parameter.

Parameters
locationThe location to redirect
statusThe HTTP status code, k302Found by default. Users could set it to one of the 301, 302, 303, 307, ...

◆ newStreamResponse()

HttpResponsePtr drogon::HttpResponse::newStreamResponse ( const std::function< std::size_t(char *, std::size_t)> & callback,
const std::string & attachmentFileName = "",
ContentType type = CT_NONE,
const std::string & typeString = "",
const HttpRequestPtr & req = HttpRequestPtr() )
static

Create a response that returns a file to the client from a callback function

Note
if the Connection is keep-alive and the Content-Length header is not set, the stream data is sent with Transfer-Encoding: chunked.
Parameters
callbackfunction to retrieve the stream data (stream ends when a zero size is returned) the callback will be called with nullptr when the send is finished/interrupted so that it cleans up its internals.
attachmentFileNameif the parameter is not empty, the browser does not open the file, but saves it as an attachment.
typethe content type code. If the parameter is CT_NONE, the content type is set by drogon based on the file extension and typeString. Set it to CT_CUSTOM when no drogon internal content type matches.
typeStringthe MIME string of the content type.

◆ operator T()

template<typename T>
drogon::HttpResponse::operator T ( ) const
inline

This template enables automatic type conversion. For using this template, user must specialize the fromResponse template. For example a shared_ptr<Json::Value> specialization version is available above, so we can use the following code to get a json object:

std::shared_ptr<Json::Value> jsonPtr = *responsePtr;

With this template, user can use their favorite JSON library instead of the default jsoncpp library or convert the response to an object of any custom type.

◆ peerCertificate()

virtual const trantor::CertificatePtr & drogon::HttpResponse::peerCertificate ( ) const
pure virtual

Get the certificate of the peer, if any.

Returns
The certificate of the peer. nullptr is none.

◆ removeHeader()

virtual void drogon::HttpResponse::removeHeader ( std::string key)
pure virtual

Remove the header identified by the key parameter.

Parameters
keyThe key is case insensitive

◆ setBody()

virtual void drogon::HttpResponse::setBody ( const std::string & body)
pure virtual

Set the response body(content).

Note
The body must match the content type

◆ setCloseConnection()

virtual void drogon::HttpResponse::setCloseConnection ( bool on)
pure virtual

Set if close the connection after the request is sent.

Parameters
onif the parameter is false, the connection keeps alive on the condition that the client request has a 'keep-alive' head, otherwise it is closed immediately after sending the last byte of the response. It's false by default when the response is created.

◆ setContentTypeCode()

virtual void drogon::HttpResponse::setContentTypeCode ( ContentType type)
pure virtual

Set the response content type, such as text/html, text/plain, image/png and so on. If the content type is a text type, the character set is utf8.

◆ setContentTypeCodeAndCustomString()

void drogon::HttpResponse::setContentTypeCodeAndCustomString ( ContentType type,
const std::string_view & typeString )
inline

Set the response content type and the content-type string, The string may contain the header name and CRLF. Or just the MIME type For example, "content-type: text/plain\r\n" or "text/plain"

◆ setContentTypeString()

void drogon::HttpResponse::setContentTypeString ( const std::string_view & typeString)
inline

Set the content-type string, The string may contain the header name and CRLF. Or just the MIME type For example, "content-type: text/plain\r\n" or "text/plain"

◆ setExpiredTime()

virtual void drogon::HttpResponse::setExpiredTime ( ssize_t expiredTime)
pure virtual

Set the expiration time of the response cache in memory. in seconds, 0 means always cache, negative means not cache, default is -1.

◆ setPassThrough()

virtual void drogon::HttpResponse::setPassThrough ( bool flag)
pure virtual

Set the response object to the pass-through mode or not. It's not by default when a new response object is created. In pass-through mode, no additional headers (including server, date, content-type and content-length, etc.) are added to the response. This mode is useful for some applications such as a proxy.

Parameters
flag

◆ version()

virtual Version drogon::HttpResponse::version ( ) const
pure virtual

Return the enum type version of the response.

kHttp10 means Http version is 1.0 kHttp11 means Http version is 1.1

◆ versionString()

virtual const char * drogon::HttpResponse::versionString ( ) const
pure virtual

Return the string of http version of request, such as HTTP/1.0, HTTP/1.1, etc.


The documentation for this class was generated from the following file: