Logo Pico-Framework A web-first embedded framework for C++
Loading...
Searching...
No Matches
HttpResponse.h
Go to the documentation of this file.
1
15#ifndef HTTPRESPONSE_H
16#define HTTPRESPONSE_H
17
18#include <string>
19#include <unordered_map>
20#include <map>
21#include <vector>
22#include <nlohmann/json.hpp>
23#include "network/Tcp.h"
26
27// Forward declaration of HttpRequest class
28class HttpRequest;
29
37{
38
39public:
40 HttpResponse() = default;
41
47
48 Tcp *getTcp() const { return tcp; }
49
50 // ------------------------------------------------------------------------
51 // Status and Header Management
52 // ------------------------------------------------------------------------
53
59 HttpResponse &status(int code);
60
64 HttpResponse &setStatus(int code);
65
70 HttpResponse &setBody(const std::string &body);
71
77 HttpResponse &setContentType(const std::string &content_type);
78
83 std::string getContentType() const;
84
91 HttpResponse &set(const std::string &field, const std::string &value);
92
96 HttpResponse &setHeader(const std::string &key, const std::string &value);
97
103 HttpResponse &setAuthorization(const std::string &jwtToken);
104
109 bool isHeaderSent() const;
110
111 // ------------------------------------------------------------------------
112 // Cookie Support
113 // ------------------------------------------------------------------------
114
122 HttpResponse &setCookie(const std::string &name, const std::string &value, const std::string &options);
123
130 HttpResponse &clearCookie(const std::string &name, const std::string &options);
131
132 // ------------------------------------------------------------------------
133 // Body and Streaming
134 // ------------------------------------------------------------------------
135
140 void send(const std::string &body);
141
142 void send(){
143 send(""); // delegate to the existing one-arg version with empty body
144 }
145
146 void send(std::nullptr_t) = delete; // prevent sending null
147
148 void send(const FrameworkView& view) {
149 send(view, {}); // delegate to the existing two-arg version with empty context
150 }
151
152 void send(const std::string &body, const std::string &contentType);
153
155
156 void send(const FrameworkView& view,
157 const std::map<std::string, std::string>& context);
158
162 void sendHeaders();
163
170 void start(int code, size_t contentLength, const std::string &contentType = "application/octet-stream",
171 const std::string &contentEncoding = "");
172
178 void writeChunk(const char *data, size_t length);
179
183 void finish();
184
185 // ------------------------------------------------------------------------
186 // Common Helpers
187 // ------------------------------------------------------------------------
192 bool ok() const
193 {
194 return status_code >= 200 && status_code < 300;
195 }
196
200 int getSocket() const;
201
205 void sendUnauthorized();
206
210 void sendNotFound();
211
216 void endServerError(const std::string &msg);
217
223 HttpResponse &json(const std::string &jsonString);
224 HttpResponse &json(const nlohmann::json &jsonObj);
225 HttpResponse &jsonFormatted(const nlohmann::json &jsonObj);
226
232 HttpResponse &text(const std::string &textString);
233
240 HttpResponse &redirect(const std::string &url, int statusCode);
241
249 bool sendFile(const std::string &path);
250
251#if defined(PICO_HTTP_ENABLE_STORAGE)
258 bool saveFile(const char *path) const;
259#endif
260
267 std::string renderTemplate(const std::string &tpl, const std::map<std::string, std::string> &context);
268
269 // ───── Shared Response API (Client and Server) ─────
270
275 int getStatusCode() const
276 {
277 return status_code;
278 }
279
285 std::string getHeader(const std::string &key) const
286 {
287 auto it = headers.find(key);
288 return (it != headers.end()) ? it->second : "";
289 }
290
295 const std::map<std::string, std::string> &getHeaders() const
296 {
297 return headers;
298 }
299
304 const std::string &getBody() const
305 {
306 return body;
307 }
308
312 void reset();
313
318 bool isBodyTruncated() const { return bodyTruncated; }
319
325
326 // Convenience wrappers enabling fluent chaining
327 HttpResponse& sendSuccess(const nlohmann::json& data = {}, const std::string& message = "");
328 HttpResponse& sendCreated(const nlohmann::json& data = {}, const std::string& message = "");
329 HttpResponse& sendMessage(const std::string& message);
331 HttpResponse& sendError(int statusCode, const std::string& code, const std::string& message);
332 HttpResponse& sendError(int statusCode, const std::string& message); // simpler form
333
334 //#if defined(PICO_HTTP_ENABLE_STORAGE)
335 HttpResponse& toFile(const std::string& path, StorageManager* storage);
336 //#endif
337
338private:
344 std::string getStatusMessage(int code);
345
347 int status_code = 200;
348 bool headerSent = false;
349 bool bodyTruncated = false;
350
351 std::map<std::string, std::string> headers;
352 std::vector<std::string> cookies;
353
354 std::string body;
355
356};
357
358#endif // HTTPRESPONSE_H
Abstract base class for all views in the PicoFramework.
nlohmann::json json
Abstract interface for file and directory storage backends.
General-purpose TCP socket abstraction with optional TLS support for both client and server use.
Forward declaration for potential routing needs.
Definition HttpRequest.h:32
Represents an HTTP response object.
void sendUnauthorized()
Send a 401 Unauthorized JSON response.
int status_code
HTTP status code.
bool isBodyTruncated() const
Check if the response body was truncated.
Tcp * getTcp() const
HttpResponse & setStatus(int code)
Alias for status().
std::string renderTemplate(const std::string &tpl, const std::map< std::string, std::string > &context)
Apply basic variable substitution in a template.
HttpResponse & toFile(const std::string &path, StorageManager *storage)
HttpResponse & setContentType(const std::string &content_type)
Set the Content-Type header.
void writeChunk(const char *data, size_t length)
Send a chunk of the response body.
HttpResponse()=default
HttpResponse & text(const std::string &textString)
Send a plain text string with correct content type.
int getStatusCode() const
Get the response status code.
void markBodyTruncated()
Mark the response body as truncated.
int getSocket() const
Return the raw socket descriptor.
HttpResponse & set(const std::string &field, const std::string &value)
Set a generic header field.
void finish()
Finish the response (placeholder for potential finalization).
bool isHeaderSent() const
Check if the headers have already been sent.
HttpResponse & setAuthorization(const std::string &jwtToken)
Set an Authorization header with a JWT token.
HttpResponse & sendCreated(const nlohmann::json &data={}, const std::string &message="")
void sendNotFound()
Send a 404 Not Found JSON response.
void endServerError(const std::string &msg)
Send a 500 Internal Server Error response.
const std::string & getBody() const
Get the response body.
bool ok() const
Check if the response status code indicates success.
HttpResponse & jsonFormatted(const nlohmann::json &jsonObj)
void sendHeaders()
Send only the headers (for chunked/streaming responses).
HttpResponse & setCookie(const std::string &name, const std::string &value, const std::string &options)
Set a cookie to be sent with the response.
HttpResponse & clearCookie(const std::string &name, const std::string &options)
Clear a cookie by setting Max-Age=0.
HttpResponse & status(int code)
Set the HTTP status code.
Tcp * tcp
Pointer to the Tcp object for socket operations.
std::string getContentType() const
Get the current Content-Type header value.
HttpResponse & sendMessage(const std::string &message)
std::string body
Full response body (client-side or buffered server content)
HttpResponse & setBody(const std::string &body)
Set the body of the response (string).
bool sendFile(const std::string &path)
Sends the specified file from mounted storage to the client.
std::vector< std::string > cookies
Set-Cookie headers (server only)
HttpResponse & redirect(const std::string &url, int statusCode)
Redirect the client to another URL.
HttpResponse & sendNoContent()
std::map< std::string, std::string > headers
Response headers (server+client)
void send(std::nullptr_t)=delete
std::string getHeader(const std::string &key) const
Get the value of a specific response header.
void send(const FrameworkView &view)
bool headerSent
Tracks whether headers have already been sent.
void reset()
Clear the response status, headers, and body.
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.
const std::map< std::string, std::string > & getHeaders() const
Get all response headers.
std::string getStatusMessage(int code)
Convert an HTTP status code to its standard message.
HttpResponse & sendSuccess(const nlohmann::json &data={}, const std::string &message="")
HttpResponse & sendError(int statusCode, const std::string &code, const std::string &message)
HttpResponse & setHeader(const std::string &key, const std::string &value)
Alias for set() for custom headers.
Abstract base class for storage access and file operations.
General-purpose TCP socket wrapper with optional TLS support via mbedTLS (altcp).
Definition Tcp.h:39