Logo Pico-Framework A web-first embedded framework for C++
Loading...
Searching...
No Matches
HttpResponse Class Reference

Represents an HTTP response object. More...

#include <HttpResponse.h>

+ Collaboration diagram for HttpResponse:

Public Member Functions

 HttpResponse ()=default
 
 HttpResponse (Tcp *tcp)
 Construct a new HttpResponse object with a socket.
 
TcpgetTcp () const
 
HttpResponsestatus (int code)
 Set the HTTP status code.
 
HttpResponsesetStatus (int code)
 Alias for status().
 
HttpResponsesetBody (const std::string &body)
 Set the body of the response (string).
 
HttpResponsesetContentType (const std::string &content_type)
 Set the Content-Type header.
 
std::string getContentType () const
 Get the current Content-Type header value.
 
HttpResponseset (const std::string &field, const std::string &value)
 Set a generic header field.
 
HttpResponsesetHeader (const std::string &key, const std::string &value)
 Alias for set() for custom headers.
 
HttpResponsesetAuthorization (const std::string &jwtToken)
 Set an Authorization header with a JWT token.
 
bool isHeaderSent () const
 Check if the headers have already been sent.
 
HttpResponsesetCookie (const std::string &name, const std::string &value, const std::string &options)
 Set a cookie to be sent with the response.
 
HttpResponseclearCookie (const std::string &name, const std::string &options)
 Clear a cookie by setting Max-Age=0.
 
void send (const std::string &body)
 Send a full response including headers and body.
 
void send ()
 
void send (std::nullptr_t)=delete
 
void send (const FrameworkView &view)
 
void send (const std::string &body, const std::string &contentType)
 
void send (const FrameworkView &view, const std::map< std::string, std::string > &context)
 
void sendHeaders ()
 Send only the headers (for chunked/streaming responses).
 
void start (int code, size_t contentLength, const std::string &contentType="application/octet-stream", const std::string &contentEncoding="")
 Begin a streaming response by sending headers.
 
void writeChunk (const char *data, size_t length)
 Send a chunk of the response body.
 
void finish ()
 Finish the response (placeholder for potential finalization).
 
bool ok () const
 Check if the response status code indicates success.
 
int getSocket () const
 Return the raw socket descriptor.
 
void sendUnauthorized ()
 Send a 401 Unauthorized JSON response.
 
void sendNotFound ()
 Send a 404 Not Found JSON response.
 
void endServerError (const std::string &msg)
 Send a 500 Internal Server Error response.
 
HttpResponsejson (const std::string &jsonString)
 Send a JSON string/object with correct content type.
 
HttpResponsejson (const nlohmann::json &jsonObj)
 
HttpResponsejsonFormatted (const nlohmann::json &jsonObj)
 
HttpResponsetext (const std::string &textString)
 Send a plain text string with correct content type.
 
HttpResponseredirect (const std::string &url, int statusCode)
 Redirect the client to another URL.
 
bool sendFile (const std::string &path)
 Sends the specified file from mounted storage to the client.
 
std::string renderTemplate (const std::string &tpl, const std::map< std::string, std::string > &context)
 Apply basic variable substitution in a template.
 
int getStatusCode () const
 Get the response status code.
 
std::string getHeader (const std::string &key) const
 Get the value of a specific response header.
 
const std::map< std::string, std::string > & getHeaders () const
 Get all response headers.
 
const std::string & getBody () const
 Get the response body.
 
void reset ()
 Clear the response status, headers, and body.
 
bool isBodyTruncated () const
 Check if the response body was truncated.
 
void markBodyTruncated ()
 Mark the response body as truncated.
 
HttpResponsesendSuccess (const nlohmann::json &data={}, const std::string &message="")
 
HttpResponsesendCreated (const nlohmann::json &data={}, const std::string &message="")
 
HttpResponsesendMessage (const std::string &message)
 
HttpResponsesendNoContent ()
 
HttpResponsesendError (int statusCode, const std::string &code, const std::string &message)
 
HttpResponsesendError (int statusCode, const std::string &message)
 
HttpResponsetoFile (const std::string &path, StorageManager *storage)
 

Private Member Functions

std::string getStatusMessage (int code)
 Convert an HTTP status code to its standard message.
 

Private Attributes

Tcptcp
 Pointer to the Tcp object for socket operations.
 
int status_code = 200
 HTTP status code.
 
bool headerSent = false
 Tracks whether headers have already been sent.
 
bool bodyTruncated = false
 
std::map< std::string, std::string > headers
 Response headers (server+client)
 
std::vector< std::string > cookies
 Set-Cookie headers (server only)
 
std::string body
 Full response body (client-side or buffered server content)
 

Detailed Description

Used by the server to construct and send headers, content, and cookies in response to an incoming HTTP request.

Examples
/home/runner/work/pico-framework-docs/pico-framework-docs/pico-framework/framework/include/http/Middleware.h.

Definition at line 36 of file HttpResponse.h.

Constructor & Destructor Documentation

◆ HttpResponse() [1/2]

HttpResponse::HttpResponse ( )
default

◆ HttpResponse() [2/2]

HttpResponse::HttpResponse ( Tcp tcp)

Construct a new HttpResponse object.

Parameters
sockThe socket file descriptor.
sockSocket descriptor for the client connection.

Definition at line 39 of file HttpResponse.cpp.

40 : tcp(tcp), status_code(200), headerSent(false)
41{
42}
int status_code
HTTP status code.
Tcp * tcp
Pointer to the Tcp object for socket operations.
bool headerSent
Tracks whether headers have already been sent.

Member Function Documentation

◆ clearCookie()

HttpResponse & HttpResponse::clearCookie ( const std::string &  name,
const std::string &  options 
)

Clear a cookie by setting Max-Age=0.

Parameters
nameCookie name.
optionsOptional options to include in the Set-Cookie header.
Returns
Reference to this HttpResponse object.
Parameters
nameCookie name.
optionsOptional options to include in the Set-Cookie header.
Returns
Reference to this HttpResponse object.

Definition at line 174 of file HttpResponse.cpp.

175{
176 std::ostringstream cookie;
177 cookie << name << "=; Max-Age=0";
178 if (!options.empty())
179 {
180 cookie << "; " << options;
181 }
182 cookies.push_back(cookie.str());
183 return *this;
184}
std::vector< std::string > cookies
Set-Cookie headers (server only)

References cookies.

◆ endServerError()

void HttpResponse::endServerError ( const std::string &  message)

Send a 500 Internal Server Error response.

Parameters
msgError message to include.
Parameters
msgError message to include.

Definition at line 342 of file HttpResponse.cpp.

343{
344 return status(500)
345 .setContentType("application/json")
346 .send("{\"error\": \"" + message + "\"}");
347}
HttpResponse & setContentType(const std::string &content_type)
Set the Content-Type header.
void send(const std::string &body)
Send a full response including headers and body.
HttpResponse & status(int code)
Set the HTTP status code.

References send(), setContentType(), and status().

+ Here is the call graph for this function:

◆ finish()

void HttpResponse::finish ( )

Finish the response (placeholder for potential finalization).

Definition at line 310 of file HttpResponse.cpp.

311{
312 // Placeholder for future expansion (e.g., chunked transfer end).
313}

Referenced by FileHandler::serveFile().

+ Here is the caller graph for this function:

◆ getBody()

const std::string & HttpResponse::getBody ( ) const
inline
Returns
Response body string

Definition at line 304 of file HttpResponse.h.

305 {
306 return body;
307 }
std::string body
Full response body (client-side or buffered server content)

References body.

Referenced by TimeManager::fetchAndApplyTimezoneFromOpenMeteo(), and TimeManager::getLocationFromIp().

+ Here is the caller graph for this function:

◆ getContentType()

std::string HttpResponse::getContentType ( ) const

Get the current Content-Type header value.

Returns
MIME type string.
Returns
MIME type string.

Definition at line 108 of file HttpResponse.cpp.

109{
110 auto it = headers.find("Content-Type");
111 return (it != headers.end()) ? it->second : "text/html";
112}
std::map< std::string, std::string > headers
Response headers (server+client)

References headers.

◆ getHeader()

std::string HttpResponse::getHeader ( const std::string &  key) const
inline
Parameters
keyHeader name
Returns
Header value (empty string if not found)

Definition at line 285 of file HttpResponse.h.

286 {
287 auto it = headers.find(key);
288 return (it != headers.end()) ? it->second : "";
289 }

References headers.

◆ getHeaders()

const std::map< std::string, std::string > & HttpResponse::getHeaders ( ) const
inline
Returns
Map of header key/value pairs

Definition at line 295 of file HttpResponse.h.

296 {
297 return headers;
298 }

References headers.

◆ getSocket()

int HttpResponse::getSocket ( ) const

Return the raw socket descriptor.

Definition at line 125 of file HttpResponse.cpp.

126{
127 return tcp->getSocketFd();
128}
int getSocketFd() const
Get the raw socket file descriptor (may be -1 for TLS-only connection).
Definition Tcp.h:124

References Tcp::getSocketFd(), and tcp.

+ Here is the call graph for this function:

◆ getStatusCode()

int HttpResponse::getStatusCode ( ) const
inline
Returns
Status code (e.g., 200)

Definition at line 275 of file HttpResponse.h.

276 {
277 return status_code;
278 }

References status_code.

Referenced by TimeManager::fetchAndApplyTimezoneFromOpenMeteo().

+ Here is the caller graph for this function:

◆ getStatusMessage()

std::string HttpResponse::getStatusMessage ( int  code)
private

Return the standard HTTP status message for a code.

Parameters
codeHTTP status code.
Returns
Corresponding message (e.g., "OK").
Parameters
codeHTTP status code.
Returns
Corresponding status message.

Definition at line 135 of file HttpResponse.cpp.

136{
137 switch (code)
138 {
139 case 200:
140 return "OK";
141 case 401:
142 return "Unauthorized";
143 case 404:
144 return "Not Found";
145 case 500:
146 return "Internal Server Error";
147 default:
148 return "";
149 }
150}

Referenced by send(), sendHeaders(), and start().

+ Here is the caller graph for this function:

◆ getTcp()

Tcp * HttpResponse::getTcp ( ) const
inline

Definition at line 48 of file HttpResponse.h.

48{ return tcp; }

References tcp.

◆ isBodyTruncated()

bool HttpResponse::isBodyTruncated ( ) const
inline
Returns
True if the body was truncated, false otherwise.

Definition at line 318 of file HttpResponse.h.

318{ return bodyTruncated; }

References bodyTruncated.

◆ isHeaderSent()

bool HttpResponse::isHeaderSent ( ) const

Check if the headers have already been sent.

Returns
True if headers have been sent, false otherwise.
Returns
True if headers have been sent, false otherwise.

Definition at line 117 of file HttpResponse.cpp.

118{
119 return headerSent;
120}

References headerSent.

◆ json() [1/2]

HttpResponse & HttpResponse::json ( const nlohmann::json &  jsonObj)

Definition at line 359 of file HttpResponse.cpp.

360{
361 return json(jsonObj.dump()); // dump() creates a compact string
362}
nlohmann::json json

◆ json() [2/2]

HttpResponse & HttpResponse::json ( const std::string &  body)

Send a JSON string/object with correct content type.

Parameters
jsonStringValid JSON content.
Returns
Reference to this HttpResponse object.
Parameters
jsonStringValid JSON content.
Returns
Reference to this HttpResponse object.

Definition at line 352 of file HttpResponse.cpp.

353{
354 this->set("Content-Type", "application/json")
355 .send(body);
356 return *this;
357}
HttpResponse & set(const std::string &field, const std::string &value)
Set a generic header field.

References send(), and set().

Referenced by DashboardController::getLedState(), GpioController::getState(), DashboardController::getTemperature(), GpioController::handleGetMultipleGpios(), App::initRoutes(), JsonResponse::sendCreated(), JsonResponse::sendError(), JsonResponse::sendJson(), JsonResponse::sendMessage(), JsonResponse::sendSuccess(), DashboardController::setLedState(), and GpioController::setState().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ jsonFormatted()

HttpResponse & HttpResponse::jsonFormatted ( const nlohmann::json &  jsonObj)

Definition at line 364 of file HttpResponse.cpp.

365{
366 return json(jsonObj.dump(2)); // dump() creates a compact string
367}

◆ markBodyTruncated()

void HttpResponse::markBodyTruncated ( )
inline

This is used when the body exceeds the maximum allowed size.

Definition at line 324 of file HttpResponse.h.

324{ bodyTruncated = true; }

References bodyTruncated.

◆ ok()

bool HttpResponse::ok ( ) const
inline
Returns
True if status code is 2xx, false otherwise.

Definition at line 192 of file HttpResponse.h.

193 {
194 return status_code >= 200 && status_code < 300;
195 }

References status_code.

◆ redirect()

HttpResponse & HttpResponse::redirect ( const std::string &  url,
int  statusCode 
)
Parameters
urlTarget URL.
statusCodeHTTP status code (e.g. 302).
Returns
Reference to this HttpResponse object.

Definition at line 379 of file HttpResponse.cpp.

380{
381 this->status(code)
382 .set("Location", url)
383 .send("");
384 return *this;
385}

References send(), set(), and status().

+ Here is the call graph for this function:

◆ renderTemplate()

std::string HttpResponse::renderTemplate ( const std::string &  tpl,
const std::map< std::string, std::string > &  context 
)

Apply basic variable substitution in a template.

Parameters
tplInput template with {{placeholders}}.
contextKey-value map for substitution.
Returns
Final rendered template string.
Parameters
tplInput template with {{placeholders}}.
contextKey-value map for substitution.
Returns
Final rendered template string.

Definition at line 390 of file HttpResponse.cpp.

391{
392 std::string result = tpl;
393 for (const auto &[key, value] : context)
394 {
395 std::string placeholder = "{{" + key + "}}";
396 size_t pos = 0;
397 while ((pos = result.find(placeholder, pos)) != std::string::npos)
398 {
399 result.replace(pos, placeholder.length(), value);
400 pos += value.length();
401 }
402 }
403 return result;
404}

◆ reset()

void HttpResponse::reset ( )

Definition at line 434 of file HttpResponse.cpp.

434 {
435 status_code = 0;
436 headers.clear();
437 body.clear();
438}

References body, headers, and status_code.

◆ send() [1/6]

void HttpResponse::send ( )
inline

Definition at line 142 of file HttpResponse.h.

142 {
143 send(""); // delegate to the existing one-arg version with empty body
144 }

References send().

Referenced by send(), send(), send(), and send().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ send() [2/6]

void HttpResponse::send ( const FrameworkView view)
inline

Definition at line 148 of file HttpResponse.h.

148 {
149 send(view, {}); // delegate to the existing two-arg version with empty context
150 }

References send().

+ Here is the call graph for this function:

◆ send() [3/6]

void HttpResponse::send ( const FrameworkView view,
const std::map< std::string, std::string > &  context 
)

Definition at line 419 of file HttpResponse.cpp.

420 {
421 view.applyHeaders(*this);
423 std::string body = view.render(context);
424 send(body);
425}
virtual std::string render(const std::map< std::string, std::string > &context={}) const =0
Render the view body.
virtual std::string getContentType() const =0
Return the MIME content type for this view.
virtual void applyHeaders(HttpResponse &response) const
Optional hook to set response headers (e.g., Content-Disposition).

References FrameworkView::applyHeaders(), body, FrameworkView::getContentType(), FrameworkView::render(), send(), and setContentType().

+ Here is the call graph for this function:

◆ send() [4/6]

void HttpResponse::send ( const std::string &  body)
Parameters
bodyHttpResponse body as a string.

Definition at line 193 of file HttpResponse.cpp.

194{
195 TRACE("HttpResponse::send()\n");
196 if (!headerSent)
197 {
198 if (headers.find("Content-Length") == headers.end())
199 {
200 headers["Content-Length"] = std::to_string(body.size());
201 }
202 if (headers.find("Content-Type") == headers.end())
203 {
204 headers["Content-Type"] = "text/html";
205 }
206
207 std::ostringstream resp;
208 resp << "HTTP/1.1 " << status_code << " " << getStatusMessage(status_code) << "\r\n";
209 for (auto &h : headers)
210 {
211 resp << h.first << ": " << h.second << "\r\n";
212 }
213 for (const auto &cookie : cookies)
214 {
215 resp << "Set-Cookie: " << cookie << "\r\n";
216 }
217 resp << "\r\n";
218
219 std::string header_str = resp.str();
220 tcp->send(header_str.c_str(), header_str.size());
221 headerSent = true;
222 }
223
224 tcp->send(body.data(), body.size());
225 TRACE("HttpResponse::send() completed\n");
226}
#define TRACE(...)
Default trace (INFO level).
Definition DebugTrace.h:187
std::string getStatusMessage(int code)
Convert an HTTP status code to its standard message.
int send(const char *buffer, size_t size)
Send data over the connection.
Definition Tcp.cpp:279

References body, cookies, getStatusMessage(), headers, headerSent, Tcp::send(), status_code, tcp, and TRACE.

Referenced by endServerError(), MultipartParser::handleMultipart(), App::initRoutes(), DashboardController::initRoutes(), json(), redirect(), HtmlTemplateView::render(), JsonResponse::sendNoContent(), sendNotFound(), sendUnauthorized(), and text().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ send() [5/6]

void HttpResponse::send ( const std::string &  body,
const std::string &  contentType 
)

Definition at line 412 of file HttpResponse.cpp.

412 {
413 setHeader("Content-Type", contentType);
414 send(body);
415}
HttpResponse & setHeader(const std::string &key, const std::string &value)
Alias for set() for custom headers.

References body, send(), and setHeader().

+ Here is the call graph for this function:

◆ send() [6/6]

void HttpResponse::send ( std::nullptr_t  )
delete

◆ sendCreated()

HttpResponse & HttpResponse::sendCreated ( const nlohmann::json &  data = {},
const std::string &  message = "" 
)

Definition at line 69 of file JsonResponse.cpp.

69 {
70 JsonResponse::sendCreated(*this, data, message);
71 return *this;
72}
void sendCreated(HttpResponse &res, const nlohmann::json &data, const std::string &message)

References JsonResponse::sendCreated().

+ Here is the call graph for this function:

◆ sendError() [1/2]

HttpResponse & HttpResponse::sendError ( int  statusCode,
const std::string &  code,
const std::string &  message 
)

Definition at line 84 of file JsonResponse.cpp.

84 {
85 JsonResponse::sendError(*this, statusCode, code, message);
86 return *this;
87}
void sendError(HttpResponse &res, int statusCode, const std::string &code, const std::string &message)

References JsonResponse::sendError().

Referenced by DashboardController::deleteFile(), and HttpFileserver::handle_list_directory().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ sendError() [2/2]

HttpResponse & HttpResponse::sendError ( int  statusCode,
const std::string &  message 
)

Definition at line 446 of file HttpResponse.cpp.

446 {
447 JsonResponse::sendError(*this, statusCode, "error", message);
448 return *this;
449}

References JsonResponse::sendError().

+ Here is the call graph for this function:

◆ sendFile()

bool HttpResponse::sendFile ( const std::string &  path)
Parameters
pathRelative path to the file (e.g. "/index.html").
Returns
true if the file was successfully sent.
false if the file was not found or an error occurred.

Definition at line 440 of file HttpResponse.cpp.

441{
442 FileHandler fileHandler;
443 return fileHandler.serveFile(*this, path.c_str());
444}
Helper class for accessing the file system and serving file content.
bool serveFile(HttpResponse &res, const char *uri)
Serve a file to the client via the HttpResponse object.

References FileHandler::serveFile().

Referenced by DashboardController::initRoutes().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ sendHeaders()

void HttpResponse::sendHeaders ( )

Send only the headers (for chunked/streaming responses).

Definition at line 231 of file HttpResponse.cpp.

232{
233 if (!headerSent)
234 {
235 std::ostringstream resp;
236 resp << "HTTP/1.1 " << status_code << " " << getStatusMessage(status_code) << "\r\n";
237
238 for (auto &h : headers)
239 {
240 resp << h.first << ": " << h.second << "\r\n";
241 }
242 for (const auto &cookie : cookies)
243 {
244 resp << "Set-Cookie: " << cookie << "\r\n";
245 }
246 if (headers.find("Connection") == headers.end())
247 {
248 resp << "Connection: close\r\n";
249 }
250 resp << "\r\n";
251
252 std::string header_str = resp.str();
253 tcp->send(header_str.c_str(), header_str.size());
254 headerSent = true;
255 }
256}

References cookies, getStatusMessage(), headers, headerSent, Tcp::send(), status_code, and tcp.

+ Here is the call graph for this function:

◆ sendMessage()

HttpResponse & HttpResponse::sendMessage ( const std::string &  message)

Definition at line 74 of file JsonResponse.cpp.

74 {
75 JsonResponse::sendMessage(*this, message);
76 return *this;
77}
void sendMessage(HttpResponse &res, const std::string &message)

References JsonResponse::sendMessage().

+ Here is the call graph for this function:

◆ sendNoContent()

HttpResponse & HttpResponse::sendNoContent ( )

Definition at line 79 of file JsonResponse.cpp.

79 {
81 return *this;
82}
void sendNoContent(HttpResponse &res)

References JsonResponse::sendNoContent().

+ Here is the call graph for this function:

◆ sendNotFound()

void HttpResponse::sendNotFound ( )

Send a 404 Not Found JSON response.

Definition at line 332 of file HttpResponse.cpp.

333{
334 return status(404)
335 .setContentType("application/json")
336 .send(R"({"error": "Not Found"})");
337}

References send(), setContentType(), and status().

+ Here is the call graph for this function:

◆ sendSuccess()

HttpResponse & HttpResponse::sendSuccess ( const nlohmann::json &  data = {},
const std::string &  message = "" 
)

Definition at line 64 of file JsonResponse.cpp.

64 {
65 JsonResponse::sendSuccess(*this, data, message);
66 return *this;
67}
void sendSuccess(HttpResponse &res, const nlohmann::json &data, const std::string &message)

References JsonResponse::sendSuccess().

Referenced by DashboardController::deleteFile(), and HttpFileserver::handle_list_directory().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ sendUnauthorized()

void HttpResponse::sendUnauthorized ( )

Send a 401 Unauthorized JSON response.

Definition at line 322 of file HttpResponse.cpp.

323{
324 this->status(401)
325 .set("Content-Type", "application/json")
326 .send("{\"error\": \"Unauthorized\"}");
327}

References send(), set(), and status().

+ Here is the call graph for this function:

◆ set()

HttpResponse & HttpResponse::set ( const std::string &  field,
const std::string &  value 
)

Set a generic header field.

Parameters
fieldHeader name.
valueHeader value.
Returns
Reference to this HttpResponse object.
Parameters
fieldHeader name.
valueHeader value.
Returns
Reference to this HttpResponse object.

Definition at line 69 of file HttpResponse.cpp.

70{
71 headers[field] = value;
72 return *this;
73}

References headers.

Referenced by json(), redirect(), sendUnauthorized(), FileHandler::serveFile(), and text().

+ Here is the caller graph for this function:

◆ setAuthorization()

HttpResponse & HttpResponse::setAuthorization ( const std::string &  jwtToken)

Set an Authorization header with a JWT token.

Parameters
jwtTokenThe JWT string.
Returns
Reference to this HttpResponse object.
Parameters
jwtTokenThe JWT string.
Returns
Reference to this HttpResponse object.

Definition at line 96 of file HttpResponse.cpp.

97{
98 if (!jwtToken.empty())
99 {
100 headers["Authorization"] = "Bearer " + jwtToken;
101 }
102 return *this;
103}

References headers.

◆ setBody()

HttpResponse & HttpResponse::setBody ( const std::string &  body)
Parameters
bodyResponse body content

Definition at line 429 of file HttpResponse.cpp.

429 {
430 this->body = body;
431 return *this;
432}

References body.

◆ setContentType()

HttpResponse & HttpResponse::setContentType ( const std::string &  ct)

Set the Content-Type header.

Parameters
content_typeMIME type string.
Returns
Reference to this HttpResponse object.
Parameters
content_typeMIME type string.
Returns
Reference to this HttpResponse object.

Definition at line 87 of file HttpResponse.cpp.

88{
89 headers["Content-Type"] = ct;
90 return *this;
91}

References headers.

Referenced by endServerError(), DashboardController::initRoutes(), HtmlTemplateView::render(), send(), and sendNotFound().

+ Here is the caller graph for this function:

◆ setCookie()

HttpResponse & HttpResponse::setCookie ( const std::string &  name,
const std::string &  value,
const std::string &  options 
)

Set a cookie to be sent with the response.

Parameters
nameCookie name.
valueCookie value.
optionsAdditional options (e.g., Path, HttpOnly).
Returns
Reference to this HttpResponse object.
Parameters
nameCookie name.
valueCookie value.
optionsAdditional options (e.g., Path, HttpOnly).
Returns
Reference to this HttpResponse object.

Definition at line 159 of file HttpResponse.cpp.

160{
161 std::ostringstream cookie;
162 cookie << name << "=" << value;
163 if (!options.empty())
164 {
165 cookie << "; " << options;
166 }
167 cookies.push_back(cookie.str());
168 return *this;
169}

References cookies.

◆ setHeader()

HttpResponse & HttpResponse::setHeader ( const std::string &  key,
const std::string &  value 
)

Alias for set() for custom headers.

Definition at line 78 of file HttpResponse.cpp.

79{
80 headers[key] = value;
81 return *this;
82}

References headers.

Referenced by HttpServer::handleClient(), and send().

+ Here is the caller graph for this function:

◆ setStatus()

HttpResponse & HttpResponse::setStatus ( int  code)

Alias for status().

Definition at line 60 of file HttpResponse.cpp.

61{
62 status_code = code;
63 return *this;
64}

References status_code.

◆ start()

void HttpResponse::start ( int  code,
size_t  contentLength,
const std::string &  contentType = "application/octet-stream",
const std::string &  contentEncoding = "" 
)

Begin a streaming response by sending headers.

Parameters
codeHTTP status code.
contentLengthTotal length of body.
contentTypeMIME type.
Parameters
codeHTTP status code.
contentLengthTotal length of body.
contentTypeMIME type.

Definition at line 261 of file HttpResponse.cpp.

262{
263 status_code = code;
264 headers["Content-Length"] = std::to_string(contentLength);
265 headers["Content-Type"] = contentType;
266 if (!contentEncoding.empty())
267 {
268 headers["Content-Encoding"] = contentEncoding;
269 }
270
271 std::ostringstream resp;
272 resp << "HTTP/1.1 " << status_code << " " << getStatusMessage(status_code) << "\r\n";
273 for (auto &h : headers)
274 {
275 resp << h.first << ": " << h.second << "\r\n";
276 }
277 for (const auto &cookie : cookies)
278 {
279 resp << "Set-Cookie: " << cookie << "\r\n";
280 }
281 resp << "\r\n";
282
283 std::string header_str = resp.str();
284 tcp->send(header_str.c_str(), header_str.size());
285 headerSent = true;
286}

References cookies, getStatusMessage(), headers, headerSent, Tcp::send(), status_code, and tcp.

Referenced by FileHandler::serveFile().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ status()

HttpResponse & HttpResponse::status ( int  code)

Set the HTTP status code.

Parameters
codeStatus code (e.g., 200, 404).
Returns
Reference to this HttpResponse object.
Parameters
codeStatus code (e.g., 200, 404).
Returns
Reference to this HttpResponse object.

Definition at line 51 of file HttpResponse.cpp.

52{
53 status_code = code;
54 return *this;
55}

References status_code.

Referenced by endServerError(), MultipartParser::handleMultipart(), redirect(), JsonResponse::sendCreated(), JsonResponse::sendError(), JsonResponse::sendJson(), JsonResponse::sendMessage(), JsonResponse::sendNoContent(), sendNotFound(), JsonResponse::sendSuccess(), and sendUnauthorized().

+ Here is the caller graph for this function:

◆ text()

HttpResponse & HttpResponse::text ( const std::string &  body)

Send a plain text string with correct content type.

Parameters
textStringText content.
Returns
Reference to this HttpResponse object.
Parameters
textStringText content.
Returns
Reference to this HttpResponse object.

Definition at line 372 of file HttpResponse.cpp.

373{
374 this->set("Content-Type", "text/plain")
375 .send(body);
376 return *this;
377}

References send(), and set().

+ Here is the call graph for this function:

◆ toFile()

HttpResponse & HttpResponse::toFile ( const std::string &  path,
StorageManager storage 
)

Definition at line 452 of file HttpResponse.cpp.

453{
454 if (!storage || body.empty())
455 return *this;
456
457 storage->writeFile(path,
458 reinterpret_cast<const unsigned char*>(body.data()),
459 body.size());
460 return *this;
461}
virtual bool writeFile(const std::string &path, const std::vector< uint8_t > &data)=0
Write a memory buffer to a file.

References body, and StorageManager::writeFile().

+ Here is the call graph for this function:

◆ writeChunk()

void HttpResponse::writeChunk ( const char *  data,
size_t  length 
)

Send a chunk of the response body.

Parameters
dataPointer to data buffer.
lengthSize of the data.
Parameters
dataPointer to data buffer.
lengthSize of the data.

Definition at line 291 of file HttpResponse.cpp.

292{
293 if (!headerSent)
294 {
295 printf("Error: writeChunk called before start()\n");
296 return;
297 }
298
299 int err = tcp->send(data, length);
300 if (err < 0)
301 {
302 printf("Error sending chunk: %zu\n", err);
303 printf("Error: %s\n", strerror(errno));
304 }
305}

References headerSent, Tcp::send(), and tcp.

Referenced by FileHandler::serveFile().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

Member Data Documentation

◆ body

std::string HttpResponse::body
private

Definition at line 354 of file HttpResponse.h.

Referenced by getBody(), reset(), send(), send(), send(), setBody(), and toFile().

◆ bodyTruncated

bool HttpResponse::bodyTruncated = false
private

Definition at line 349 of file HttpResponse.h.

Referenced by isBodyTruncated(), and markBodyTruncated().

◆ cookies

std::vector<std::string> HttpResponse::cookies
private

Definition at line 352 of file HttpResponse.h.

Referenced by clearCookie(), send(), sendHeaders(), setCookie(), and start().

◆ headers

std::map<std::string, std::string> HttpResponse::headers
private

◆ headerSent

bool HttpResponse::headerSent = false
private

Definition at line 348 of file HttpResponse.h.

Referenced by isHeaderSent(), send(), sendHeaders(), start(), and writeChunk().

◆ status_code

int HttpResponse::status_code = 200
private

Definition at line 347 of file HttpResponse.h.

Referenced by getStatusCode(), ok(), reset(), send(), sendHeaders(), setStatus(), start(), and status().

◆ tcp

Tcp* HttpResponse::tcp
private

Definition at line 346 of file HttpResponse.h.

Referenced by getSocket(), getTcp(), send(), sendHeaders(), start(), and writeChunk().


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