cutelyst 3.9.1
A C++ Web Framework built on top of Qt, using the simple approach of Catalyst (Perl) framework.
Public Types | Public Member Functions | Protected Member Functions | Friends | List of all members
Cutelyst::Response Class Referencefinal
Inheritance diagram for Cutelyst::Response:
Inheritance graph
[legend]

Public Types

enum  CloseCode {
  CloseCodeNormal , CloseCodeGoingAway , CloseCodeProtocolError , CloseCodeDatatypeNotSupported ,
  CloseCodeReserved1004 , CloseCodeMissingStatusCode , CloseCodeAbnormalDisconnection , CloseCodeWrongDatatype ,
  CloseCodePolicyViolated , CloseCodeTooMuchData , CloseCodeMissingExtension , CloseCodeBadOperation ,
  CloseCodeTlsHandshakeFailed
}
 
enum  HttpStatus {
  Continue , SwitchingProtocols , OK , Created ,
  Accepted , NonAuthoritativeInformation , NoContent , ResetContent ,
  PartialContent , MultiStatus , MultipleChoices , MovedPermanently ,
  Found , SeeOther , NotModified , UseProxy ,
  TemporaryRedirect , PermanentRedirect , BadRequest , Unauthorized ,
  PaymentRequired , Forbidden , NotFound , MethodNotAllowed ,
  NotAcceptable , ProxyAuthenticationRequired , RequestTimeout , Conflict ,
  Gone , LengthRequired , PreconditionFailed , RequestEntityTooLarge ,
  RequestURITooLong , UnsupportedMediaType , RequestedRangeNotSatisfiable , ExpectationFailed ,
  InternalServerError , NotImplemented , BadGateway , ServiceUnavailable ,
  GatewayTimeout , HTTPVersionNotSupported , BandwidthLimitExceeded
}
 

Public Member Functions

Q_REQUIRED_RESULT QByteArray & body ()
 
QIODevice * bodyDevice () const
 
QString contentEncoding () const
 
qint64 contentLength () const
 
QString contentType () const
 
QString contentTypeCharset () const
 
QVariant cookie (const QByteArray &name) const
 
QList< QNetworkCookie > cookies () const
 
bool hasBody () const noexcept
 
QString header (const QString &field) const
 
Headersheaders () noexcept
 
bool isFinalizedHeaders () const noexcept
 
virtual bool isSequential () const noexcept override
 
QUrl location () const noexcept
 
void redirect (const QString &url, quint16 status=Found)
 
void redirect (const QUrl &url, quint16 status=Found)
 
void redirectSafe (const QUrl &url, const QUrl &fallback)
 
int removeCookies (const QByteArray &name)
 
void setBody (const QByteArray &body)
 
void setBody (const QString &body)
 
void setBody (QIODevice *body)
 
void setBody (QStringView body)
 
void setContentEncoding (const QString &encoding)
 
void setContentLength (qint64 length)
 
void setContentType (const QString &type)
 
void setCookie (const QNetworkCookie &cookie)
 
void setCookies (const QList< QNetworkCookie > &cookies)
 
void setHeader (const QString &field, const QString &value)
 
void setJsonArrayBody (const QJsonArray &array)
 
void setJsonBody (const QByteArray &json)
 
void setJsonBody (const QJsonDocument &documment)
 
void setJsonBody (const QString &json)
 
void setJsonBody (QStringView json)
 
void setJsonObjectBody (const QJsonObject &object)
 
void setStatus (quint16 status) noexcept
 
virtual qint64 size () const noexcept override
 
quint16 status () const noexcept
 
bool webSocketBinaryMessage (const QByteArray &message)
 Sends a WebSocket binary message.
 
bool webSocketClose (quint16 code=Response::CloseCodeNormal, const QString &reason={})
 Sends a WebSocket close frame, with both optional close code and a string reason.
 
bool webSocketHandshake (const QString &key={}, const QString &origin={}, const QString &protocol={})
 Sends the websocket handshake, if no parameters are defined it will use header data.
 
bool webSocketPing (const QByteArray &payload={})
 Sends a WebSocket ping with an optional payload limited to 125 bytes, which will be truncated if larger.
 
bool webSocketTextMessage (const QString &message)
 Sends a WebSocket text message.
 

Protected Member Functions

 Response (const Headers &defaultHeaders, EngineRequest *conn=nullptr)
 
virtual qint64 readData (char *data, qint64 maxlen) override
 
virtual qint64 writeData (const char *data, qint64 len) override
 

Friends

class Application
 
class Context
 
class ContextPrivate
 
class Engine
 
class EngineConnection
 

Detailed Description

Definition at line 24 of file response.h.

Member Enumeration Documentation

◆ CloseCode

This enum type specifies the status response to be sent to the client

Definition at line 78 of file response.h.

◆ HttpStatus

This enum type specifies the status response to be sent to the client

Definition at line 30 of file response.h.

Constructor & Destructor Documentation

◆ ~Response()

Response::~Response ( )
overridevirtual

Definition at line 58 of file response.cpp.

◆ Response()

Response::Response ( const Headers defaultHeaders,
EngineRequest conn = nullptr 
)
explicitprotected

Constructs a Response object, for this engine request and defaultHeaders.

Definition at line 17 of file response.cpp.

Member Function Documentation

◆ body()

QByteArray & Response::body ( )

This function returns a reference to a QByteArray which implicity sets the body device to a QBuffer, even if one was already set.

Definition at line 83 of file response.cpp.

Referenced by Cutelyst::EngineRequest::finalizeBody(), setBody(), setBody(), setJsonArrayBody(), setJsonBody(), and setJsonObjectBody().

◆ bodyDevice()

QIODevice * Response::bodyDevice ( ) const

Returns the body IO device (if any) of this response.

Definition at line 94 of file response.cpp.

Referenced by Cutelyst::EngineRequest::finalizeBody().

◆ contentEncoding()

QString Response::contentEncoding ( ) const

Short for headers().contentEncoding();

Definition at line 158 of file response.cpp.

◆ contentLength()

qint64 Response::contentLength ( ) const

Short for headers().contentLength();

Definition at line 175 of file response.cpp.

◆ contentType()

QString Response::contentType ( ) const

Short for headers().contentType();

Definition at line 192 of file response.cpp.

Referenced by Cutelyst::RenderView::doExecute().

◆ contentTypeCharset()

QString Response::contentTypeCharset ( ) const

Short for headers().contentTypeCharset();

Definition at line 198 of file response.cpp.

◆ cookie()

QVariant Response::cookie ( const QByteArray &  name) const

Returns the first QNetworkCookie matching the name or a null QVariant if not found

Definition at line 204 of file response.cpp.

Referenced by setCookie(), and setCookies().

◆ cookies()

QList< QNetworkCookie > Response::cookies ( ) const

Returns a list of all cookies set

Definition at line 218 of file response.cpp.

Referenced by Cutelyst::EngineRequest::finalizeCookies(), and setCookies().

◆ hasBody()

bool Response::hasBody ( ) const
noexcept

Returns true if a body device has been defined as QByteArray or QIODevice or write() was called and it's on chunked mode

Definition at line 76 of file response.cpp.

Referenced by Cutelyst::RenderView::doExecute().

◆ header()

QString Cutelyst::Response::header ( const QString &  field) const

Shortcut headers().header()

◆ headers()

Headers & Cutelyst::Response::headers ( )
noexcept

Returns a reference to the response headers class

Referenced by Cutelyst::EngineRequest::finalizeCookies(), and Cutelyst::EngineRequest::finalizeHeaders().

◆ isFinalizedHeaders()

bool Cutelyst::Response::isFinalizedHeaders ( ) const
noexcept

Returns if Headers are finalized (sent to the client)

◆ isSequential()

virtual bool Cutelyst::Response::isSequential ( ) const
overridevirtualnoexcept

Writing to user-agent is always sequential

◆ location()

QUrl Cutelyst::Response::location ( ) const
noexcept

Returns the HTTP location set by the redirect

Referenced by redirect().

◆ readData()

qint64 Response::readData ( char *  data,
qint64  maxlen 
)
overrideprotectedvirtual

Reimplemented from QIODevice::readData().

Definition at line 23 of file response.cpp.

◆ redirect() [1/2]

void Cutelyst::Response::redirect ( const QString &  url,
quint16  status = Found 
)

Causes the response to redirect to the specified URL. The default status is 302. This is a convenience method that sets the Location header to the redirect destination, and then sets the response status. You will want to return false or c->detach() to interrupt the normal processing flow if you want the redirect to occur straight away.

Note
do not give a relative URL as $url, i.e: one that is not fully qualified ("http://...", etc.) or that starts with a slash "/path/here". While it may work, it is not guaranteed to do the right thing and is not a standard behaviour. You may opt to use uriFor() or uriForAction() instead.

◆ redirect() [2/2]

void Response::redirect ( const QUrl &  url,
quint16  status = Found 
)

Causes the response to redirect to the specified URL. The default status is 302. This is a convenience method that sets the Location header to the redirect destination, and then sets the response status. You will want to return false or c->detach() to interrupt the normal processing flow if you want the redirect to occur straight away.

Note
do not give a relative URL as $url, i.e: one that is not fully qualified ("http://...", etc.) or that starts with a slash "/path/here". While it may work, it is not guaranteed to do the right thing and is not a standard behaviour. You may opt to use uriFor() or uriForAction() instead.

Definition at line 278 of file response.cpp.

References location(), setBody(), and status().

Referenced by Cutelyst::LangSelect::fromPath().

◆ redirectSafe()

void Cutelyst::Response::redirectSafe ( const QUrl &  url,
const QUrl &  fallback 
)

Open Redirect Vulnerability is when you get an user provided URL and redirect to it without checking if it's safe.

This can be used on login forms that receive some "redir" parameter that once logged in allows the user to go straight to that page instead of some home page.

It's then possible to receive a link like http://example.com/login?redir=http://exemple.com/login notice how both domain names are similar for malicious porpuses, once logged in it redirects to a similar login page that will pretent the auth didn't work, user might then type their credentials on that page.

This method validades that the url scheme, domain name and port are the same of the request to your server if it isn't it will send the user to fallback url that you know it's safe. If you need to redirect the user to some other domain/port validate the URL manually an use the regular

See also
redirect method instead.

◆ removeCookies()

int Response::removeCookies ( const QByteArray &  name)

Removes all cookies that matches name, returning the number of cookies removed

Definition at line 264 of file response.cpp.

◆ setBody() [1/4]

void Response::setBody ( const QByteArray &  body)

Sets a QByteArray as the response body, content length will be automatically set to it's size.

Definition at line 114 of file response.cpp.

References body().

◆ setBody() [2/4]

void Cutelyst::Response::setBody ( const QString &  body)
inline

Sets a QString as the response body, the output will be UTF-8 and content length will be automatically set to it's size.

Definition at line 458 of file response.h.

References setBody().

◆ setBody() [3/4]

void Response::setBody ( QIODevice *  body)

Sets an IO device as the response body, the open mode must be at least QIODevice::ReadOnly. This function takes ownership of your device deleting after the request has completed

Definition at line 100 of file response.cpp.

References body().

Referenced by Cutelyst::EngineRequest::finalizeError(), redirect(), Cutelyst::CuteleeView::render(), Cutelyst::GrantleeView::render(), setBody(), and setBody().

◆ setBody() [4/4]

void Cutelyst::Response::setBody ( QStringView  body)
inline

Sets a QString as the response body, the output will be UTF-8 and content length will be automatically set to it's size.

Definition at line 463 of file response.h.

References setBody().

◆ setContentEncoding()

void Cutelyst::Response::setContentEncoding ( const QString &  encoding)

Short for headers().setContentEncoding(encoding);

Definition at line 164 of file response.cpp.

◆ setContentLength()

void Response::setContentLength ( qint64  length)

Short for headers().setContentLength(length);

Definition at line 181 of file response.cpp.

◆ setContentType()

void Cutelyst::Response::setContentType ( const QString &  type)
inline

Short for headers().setContentType(type);

Definition at line 220 of file response.h.

Referenced by Cutelyst::RenderView::doExecute(), Cutelyst::EngineRequest::finalizeError(), and Cutelyst::ViewJson::render().

◆ setCookie()

void Response::setCookie ( const QNetworkCookie &  cookie)

Defines a QNetworkCookie to be sent to the user-agent, if a previous cookie->name() was set it will be replaced

Definition at line 232 of file response.cpp.

References cookie().

◆ setCookies()

void Response::setCookies ( const QList< QNetworkCookie > &  cookies)

Defines a list of QNetworkCookie to be sent to the user-agent, all previous matches to cookie->name() will be preserved.

Definition at line 246 of file response.cpp.

References cookie(), and cookies().

◆ setHeader()

void Cutelyst::Response::setHeader ( const QString &  field,
const QString &  value 
)

◆ setJsonArrayBody()

void Response::setJsonArrayBody ( const QJsonArray &  array)

Sets a QJsonArray on a QJsonDocument as the response body, using toJson(QJsonDocument::Compact) output and setting content-type to application/json.

Definition at line 150 of file response.cpp.

References body().

◆ setJsonBody() [1/4]

void Response::setJsonBody ( const QByteArray &  json)

Sets a JSON string as the response body, this method is provided for convenience as it sets the content-type to application/json.

Definition at line 135 of file response.cpp.

◆ setJsonBody() [2/4]

void Response::setJsonBody ( const QJsonDocument &  documment)

Sets a QJsonDocument as the response body, using toJson(QJsonDocument::Compact) output and setting content-type to application/json.

Definition at line 120 of file response.cpp.

References body().

Referenced by setJsonBody().

◆ setJsonBody() [3/4]

void Response::setJsonBody ( const QString &  json)

Sets a JSON string as the response body, this method is provided for convenience as it sets the content-type to application/json.

Definition at line 128 of file response.cpp.

◆ setJsonBody() [4/4]

void Cutelyst::Response::setJsonBody ( QStringView  json)
inline

Sets a JSON string as the response body, this method is provided for convenience as it sets the content-type to application/json.

Definition at line 468 of file response.h.

References setJsonBody().

◆ setJsonObjectBody()

void Response::setJsonObjectBody ( const QJsonObject &  object)

Sets a QJsonObject on a QJsonDocument as the response body, using toJson(QJsonDocument::Compact) output and setting content-type to application/json.

Definition at line 142 of file response.cpp.

References body().

◆ setStatus()

void Response::setStatus ( quint16  status)
noexcept

Sets the response code status

Definition at line 70 of file response.cpp.

Referenced by Cutelyst::RenderView::doExecute(), and Cutelyst::EngineRequest::finalizeError().

◆ size()

virtual qint64 Cutelyst::Response::size ( ) const
overridevirtualnoexcept

Reimplemented from QIODevice::readData().

Referenced by Cutelyst::EngineRequest::finalizeHeaders().

◆ status()

quint16 Response::status ( ) const
noexcept

The current response code status

Definition at line 64 of file response.cpp.

Referenced by Cutelyst::RenderView::doExecute(), Cutelyst::EngineRequest::finalizeHeaders(), and redirect().

◆ webSocketClose()

bool Cutelyst::Response::webSocketClose ( quint16  code = Response::CloseCodeNormal,
const QString &  reason = {} 
)
Note
This method does not emit Request::webSocketClosed() signal. If you need to track when the connection was closed, the proper way is to rely on Context::destroyed() signal.

◆ webSocketHandshake()

bool Cutelyst::Response::webSocketHandshake ( const QString &  key = {},
const QString &  origin = {},
const QString &  protocol = {} 
)

Returns true in case of success, false otherwise, which can be due missing support on the engine or missing the appropriate headers.

Note
Most WebSockets client doesn't handle when a call to a WebSocket endpoint ends on an HTTP authentication failure or other HTTP status that is not the update. Due that it's best to always do the proper websocket handshake and then
See also
webSocketClose() the connection, with some meaning reason.

◆ webSocketPing()

bool Cutelyst::Response::webSocketPing ( const QByteArray &  payload = {})
Note
Some front-end servers will close the conetion if no activity is seem, NGINX closes in 60 seconds by default, in order to avoid that, sending a ping is the best to way to keep the connection alive and to know that your client is still there.

◆ writeData()

qint64 Response::writeData ( const char *  data,
qint64  len 
)
overrideprotectedvirtual

Writes data to the response body, this will flush all response headers first and will enter in chunked mode if Transfer-Encoding header is set to chunked or if no content length is set and status is not 1xx or 204 (NoContent) or 304 (NotModified)

Definition at line 30 of file response.cpp.

Friends And Related Symbol Documentation

◆ Application

friend class Application
friend

Definition at line 451 of file response.h.

◆ Context

friend class Context
friend

Definition at line 454 of file response.h.

◆ ContextPrivate

friend class ContextPrivate
friend

Definition at line 455 of file response.h.

◆ Engine

friend class Engine
friend

Definition at line 452 of file response.h.

◆ EngineConnection

friend class EngineConnection
friend

Definition at line 453 of file response.h.