Safeheron-SGX-Native-Development-Framework v1.2.0
Loading...
Searching...
No Matches
ssgx_http_t_structs.h
Go to the documentation of this file.
1#ifndef SAFEHERON_SGX_TRUSTED_HTTP_STRUCT_H
2#define SAFEHERON_SGX_TRUSTED_HTTP_STRUCT_H
3#include <any>
4#include <map>
5#include <string>
6#include <unordered_map>
7namespace ssgx {
8namespace http_t {
9// Enum for HTTP Status Codes, used to represent various response states
10enum class HttpStatusCode {
11 // Informational responses
12 Continue100 = 100,
14 Processing102 = 102,
15 EarlyHints103 = 103,
16
17 // Successful responses
18 OK200 = 200,
19 Created201 = 201,
20 Accepted202 = 202,
22 NoContent204 = 204,
23 ResetContent205 = 205,
24 PartialContent206 = 206,
25 MultiStatus207 = 207,
26 AlreadyReported208 = 208,
27 IMUsed226 = 226,
28
29 // Redirection responses
30 MultipleChoices300 = 300,
32 Found302 = 302,
33 SeeOther303 = 303,
34 NotModified304 = 304,
35 UseProxy305 = 305,
36 Unused306 = 306,
39
40 // Client error responses
41 BadRequest400 = 400,
42 Unauthorized401 = 401,
43 PaymentRequired402 = 402,
44 Forbidden403 = 403,
45 NotFound404 = 404,
47 NotAcceptable406 = 406,
49 RequestTimeout408 = 408,
50 Conflict409 = 409,
51 Gone410 = 410,
52 LengthRequired411 = 411,
54 PayloadTooLarge413 = 413,
55 UriTooLong414 = 414,
59 ImATeapot418 = 418,
62 Locked423 = 423,
64 TooEarly425 = 425,
65 UpgradeRequired426 = 426,
67 TooManyRequests429 = 429,
70
71 // Server error responses
73 NotImplemented501 = 501,
74 BadGateway502 = 502,
76 GatewayTimeout504 = 504,
80 LoopDetected508 = 508,
81 NotExtended510 = 510,
83};
84
88struct ci {
96 bool operator()(const std::string& s1, const std::string& s2) const {
97 return std::lexicographical_compare(
98 s1.begin(), s1.end(), s2.begin(), s2.end(),
99 [](unsigned char c1, unsigned char c2) { return ::tolower(c1) < ::tolower(c2); });
100 }
101};
102
103using TypeHeaders = std::map<std::string, std::string, ci>;
104using TypeParams = std::map<std::string, std::string>;
105
109class Request {
110 public:
120 void SetMethod(const char* buf, size_t buf_len);
121
129 void SetMethod(const std::string& method);
130
138 std::string Method() const;
139
149 void SetPath(const char* buf, size_t buf_len);
150
158 void SetPath(const std::string& path);
159
167 std::string Path() const;
168
176 void SetHeaders(const TypeHeaders& headers);
177
185 const TypeHeaders& Headers() const;
186
195 void SetHeader(const std::string& key, const std::string& val);
196
205 void SetHeader(const std::string& key, int64_t val);
206
215 bool HasHeader(const std::string& key) const;
216
226 std::string GetHeaderValue(const std::string& key, const char* def = "") const;
227
238 uint64_t GetHeaderValueUint64(const std::string& key, uint64_t def = 0) const;
239
247 void SetParams(const TypeParams& params);
248
256 const TypeParams& Params() const;
257
266 void SetParam(const std::string& key, const std::string& val);
267
276 void SetParam(const std::string& key, int64_t val);
277
286 bool HasParam(const std::string& key) const;
287
298 std::string GetParamValue(const std::string& key, const char* def = "") const;
299
308 void SetBody(const char* buf, size_t buf_len);
309
317 void SetBody(const std::string& body);
318
326 const std::string& Body() const;
327
336 bool FromJsonStr(const std::string& json_str);
337
346 bool FromJsonStr(const char* json_str);
347
356 bool ToJsonStr(std::string& json_str) const;
357
368 template <typename T>
369 void SetAttribute(const std::string& key, T&& value) {
370 data_[key] = std::forward<T>(value);
371 }
372
383 template <typename T>
384 T& GetAttribute(const std::string& key) {
385 return GetInternal<T>(key);
386 }
387
396 template <typename T>
397 [[maybe_unused]] [[nodiscard]] bool HasAttribute(const std::string& key) const {
398 auto it = data_.find(key);
399 return (it != data_.end() && it->second.type() == typeid(T));
400 }
401
402 private:
403 std::string method_;
404 std::string path_; //"/api/v1/xxx"
405 TypeParams params_;
406 TypeHeaders headers_;
407 std::string body_;
408 std::unordered_map<std::string, std::any> data_;
409
410 // 内部通用的 `Get` 逻辑,避免代码重复
411 template <typename T>
412 T& GetInternal(const std::string& key) {
413 auto it = data_.find(key);
414 if (it == data_.end()) {
415 throw std::runtime_error("Key '" + key + "' not found in Attribute");
416 }
417 return std::any_cast<T&>(it->second);
418 }
419};
420
424class Response {
425 public:
434
443
451 void SetHeaders(const TypeHeaders& headers);
452
460 const TypeHeaders& Headers() const;
461
470 void SetHeader(const std::string& key, const std::string& val);
471
480 void SetHeader(const std::string& key, int64_t val);
481
490 bool HasHeader(const std::string& key) const;
491
501 std::string GetHeaderValue(const std::string& key, const char* def = "") const;
502
513 uint64_t GetHeaderValueUint64(const std::string& key, uint64_t def = 0) const;
514
523 void SetBody(const char* buf, size_t buf_len);
524
532 void SetBody(const std::string& body);
533
541 const std::string& Body() const;
542
551 bool FromJsonStrWithoutBody(const std::string& json_str);
552
561 bool ToJsonStrWithoutBody(std::string& json_str) const;
562
573 void SetResp(const char* s, size_t n, const std::string& content_type, HttpStatusCode status);
574
584 void SetResp(const std::string& s, const std::string& content_type, HttpStatusCode status);
585
594 void SetRespRedirect(const std::string& url, HttpStatusCode status_code = HttpStatusCode::Found302);
595
602
609
616
623
624 private:
626 TypeHeaders headers_;
627 std::string body_;
628};
629
630} // namespace http_t
631} // namespace ssgx
632
633#endif // SAFEHERON_SGX_TRUSTED_HTTP_STRUCT_H
HTTP request class to represent an incoming HTTP request.
Definition ssgx_http_t_structs.h:109
bool HasHeader(const std::string &key) const
Check if the request has a specific header.
void SetPath(const std::string &path)
Set the path of the request (e.g., "/api/v1/xxx").
void SetMethod(const std::string &method)
Set the HTTP method (GET, POST, etc.) from a string.
const TypeHeaders & Headers() const
Get the headers for the request.
std::string Path() const
Get the path of the request.
bool HasAttribute(const std::string &key) const
Check if an attribute exists.
Definition ssgx_http_t_structs.h:397
T & GetAttribute(const std::string &key)
Get the attribute value associated with the given key.
Definition ssgx_http_t_structs.h:384
std::string Method() const
Get the HTTP method.
uint64_t GetHeaderValueUint64(const std::string &key, uint64_t def=0) const
Get the value of a specific header as uint64 (with a default value).
bool HasParam(const std::string &key) const
Check if the request has a specific parameter.
void SetPath(const char *buf, size_t buf_len)
Set the path of the request (e.g., "/api/v1/xxx").
void SetParam(const std::string &key, const std::string &val)
Set a specific parameter for the request.
const std::string & Body() const
Get the body of the request.
const TypeParams & Params() const
Get the parameters for the request.
bool FromJsonStr(const char *json_str)
Parse the request from a JSON character buffer.
void SetHeader(const std::string &key, const std::string &val)
Set a specific header for the request.
void SetAttribute(const std::string &key, T &&value)
Get the attribute value associated with the given key.
Definition ssgx_http_t_structs.h:369
void SetParams(const TypeParams &params)
Set the parameters for the request.
std::string GetHeaderValue(const std::string &key, const char *def="") const
Get the value of a specific header (with a default value).
void SetParam(const std::string &key, int64_t val)
Set a specific parameter for the request with an integer value.
void SetBody(const std::string &body)
Set the body of the request from a string.
void SetBody(const char *buf, size_t buf_len)
Set the body of the request from a character buffer.
void SetHeaders(const TypeHeaders &headers)
Set the headers for the request.
bool ToJsonStr(std::string &json_str) const
Convert the request to a JSON string.
void SetMethod(const char *buf, size_t buf_len)
Set the HTTP method (GET, POST, etc.) from a char buffer.
bool FromJsonStr(const std::string &json_str)
Parse the request from a JSON string.
std::string GetParamValue(const std::string &key, const char *def="") const
Get the value of a specific parameter (with a default value).
void SetHeader(const std::string &key, int64_t val)
Set a specific header for the request with an integer value.
HTTP response class to represent an outgoing HTTP response.
Definition ssgx_http_t_structs.h:424
uint64_t GetHeaderValueUint64(const std::string &key, uint64_t def=0) const
Get the value of a specific header as uint64 (with a default value).
bool FromJsonStrWithoutBody(const std::string &json_str)
Parse the response from a JSON string, without including the body.
std::string GetHeaderValue(const std::string &key, const char *def="") const
Get the value of a specific header in the response (with a default value).
void SetBody(const std::string &body)
Set the body of the response from a string.
HttpStatusCode StatusCode() const
Get the HTTP status code of the response.
void SetResp404NotFound()
Set a "404 Not Found" response.
void SetResp500InternalServerError()
Set a "500 Internal Server Error" response.
void SetResp(const std::string &s, const std::string &content_type, HttpStatusCode status)
Set the full response with a string body, content type, and status.
const std::string & Body() const
Get the body of the response.
void SetResp204NoContent()
Set a "204 No Content" response.
bool HasHeader(const std::string &key) const
Check if the response has a specific header.
void SetHeader(const std::string &key, int64_t val)
Set a specific header for the response with an integer value.
void SetHeaders(const TypeHeaders &headers)
Set the headers for the response.
void SetResp403Forbidden()
Set a "403 Forbidden" response.
void SetBody(const char *buf, size_t buf_len)
Set the body of the response from a character buffer.
bool ToJsonStrWithoutBody(std::string &json_str) const
Convert the response to a JSON string, without including the body.
void SetResp(const char *s, size_t n, const std::string &content_type, HttpStatusCode status)
Set the full response with a string body, content type, and status.
void SetStatusCode(HttpStatusCode status)
Set the HTTP status code for the response.
void SetRespRedirect(const std::string &url, HttpStatusCode status_code=HttpStatusCode::Found302)
Set a redirection response with the specified URL and status.
void SetHeader(const std::string &key, const std::string &val)
Set a specific header for the response.
const TypeHeaders & Headers() const
Get the headers of the response.
std::map< std::string, std::string, ci > TypeHeaders
Definition ssgx_http_t_structs.h:103
std::map< std::string, std::string > TypeParams
Definition ssgx_http_t_structs.h:104
HttpStatusCode
Definition ssgx_http_t_structs.h:10
@ PreconditionFailed412
412: Precondition failed
@ FailedDependency424
424: Failed dependency
@ PreconditionRequired428
428: Precondition required
@ ServiceUnavailable503
503: Service unavailable
@ TemporaryRedirect307
307: Temporary redirect
@ BadRequest400
400: Bad request
@ UnprocessableContent422
422: Unprocessable content
@ LengthRequired411
411: Length required
@ Created201
201: Resource was created
@ PayloadTooLarge413
413: Payload too large
@ OK200
200: Request was successful
@ TooManyRequests429
429: Too many requests
@ NoContent204
204: No content in the response
@ EarlyHints103
103: Early hints for request
@ Unauthorized401
401: Unauthorized
@ ImATeapot418
418: I'm a teapot (a joke error code)
@ UpgradeRequired426
426: Upgrade required
@ NetworkAuthenticationRequired511
511: Network authentication required
@ MovedPermanently301
301: Moved permanently
@ Processing102
102: Processing request
@ NotModified304
304: Not modified
@ Continue100
100: Continue with request
@ PartialContent206
206: Partial content
@ MisdirectedRequest421
421: Misdirected request
@ RequestTimeout408
408: Request timeout
@ AlreadyReported208
208: Already reported
@ RequestHeaderFieldsTooLarge431
431: Request header fields too large
@ ResetContent205
205: Reset content
@ BadGateway502
502: Bad gateway
@ Forbidden403
403: Forbidden
@ UnavailableForLegalReasons451
451: Unavailable for legal reasons
@ PaymentRequired402
402: Payment required
@ Unused306
306: Reserved (no longer in use)
@ UriTooLong414
414: URI too long
@ InsufficientStorage507
507: Insufficient storage
@ LoopDetected508
508: Loop detected
@ SeeOther303
303: See other location
@ UnsupportedMediaType415
415: Unsupported media type
@ HttpVersionNotSupported505
505: HTTP version not supported
@ Accepted202
202: Request has been accepted
@ RangeNotSatisfiable416
416: Range not satisfiable
@ NonAuthoritativeInformation203
203: Non-authoritative information
@ ExpectationFailed417
417: Expectation failed
@ MultipleChoices300
300: Multiple choices available
@ NotImplemented501
501: Not implemented
@ InternalServerError500
500: Internal server error
@ MultiStatus207
207: Multi-status response
@ ProxyAuthenticationRequired407
407: Proxy authentication required
@ PermanentRedirect308
308: Permanent redirect
@ MethodNotAllowed405
405: Method not allowed
@ NotAcceptable406
406: Not acceptable
@ GatewayTimeout504
504: Gateway timeout
@ VariantAlsoNegotiates506
506: Variant also negotiates
@ NotExtended510
510: Not extended
@ SwitchingProtocol101
101: Switching Protocols
Definition ssgx_attestation_t.h:6
Comparator for case-insensitive string comparison.
Definition ssgx_http_t_structs.h:88
bool operator()(const std::string &s1, const std::string &s2) const
This function compares two strings lexicographically, ignoring case.
Definition ssgx_http_t_structs.h:96