Compare commits

...

12 Commits
dev ... testing

  1. 2
      .gitignore
  2. 24
      .vscode/settings.json
  3. 73
      LICENSE
  4. 25
      lib/api.hpp
  5. 116
      lib/elementary.hpp
  6. 31
      lib/http.hpp
  7. 46
      src/api.cpp
  8. 108
      src/elementary.cpp
  9. 83
      src/http.cpp
  10. 35
      test/test.cpp
  11. BIN
      test/test.o

2
.gitignore vendored

@ -0,0 +1,2 @@
.vscode
test/*.o

@ -44,6 +44,28 @@
"limits": "cpp",
"numbers": "cpp",
"stdexcept": "cpp",
"typeinfo": "cpp"
"typeinfo": "cpp",
"csignal": "cpp",
"cstring": "cpp",
"ctime": "cpp",
"any": "cpp",
"bitset": "cpp",
"chrono": "cpp",
"codecvt": "cpp",
"complex": "cpp",
"condition_variable": "cpp",
"list": "cpp",
"set": "cpp",
"optional": "cpp",
"ratio": "cpp",
"iomanip": "cpp",
"mutex": "cpp",
"semaphore": "cpp",
"sstream": "cpp",
"stop_token": "cpp",
"thread": "cpp",
"cinttypes": "cpp",
"typeindex": "cpp",
"variant": "cpp"
}
}

@ -0,0 +1,73 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [2023] [Marcel Bandić - marcelb96@yahoo.com]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

@ -6,29 +6,18 @@
#include <vector>
#include <map>
// #include "elementary.hpp"
#include "http.hpp"
namespace marcelb {
using namespace std;
class http_request;
class http_response;
class defapi {
public:
vector<string> methods;
vector<string> paths;
vector<string> keys;
map<string, vector<string>> val_matrix;
defapi(const vector<string> _methods, const vector<string> _paths, const vector<string> _keys);
void necessary(const string _path, const vector<string> _keys);
};
class api {
public:
defapi* def;
string method;
string path;
map<string, string> params;
@ -36,11 +25,11 @@ class api {
string body;
// odlazni api zahtjev
api(defapi* _def, const string _method, const string _path, const map<string, string> _params = {}, const string _body = {});
api(const http_method _method, const string _path, const map<string, string> _params = {}, const string _body = {});
// dolazni api zahjtev
api(defapi* _def, const http_request _req);
// bool validate();
api(const http_request _req);
};
}
#endif

@ -0,0 +1,116 @@
#ifndef _HTTP_ELMY_
#define _HTTP_ELMY_
#include <string>
using namespace std;
namespace marcelb {
typedef enum {
GET=0, POST=1, PUT=2, DEL=3, PATCH=4, get=GET, post=POST, put=PUT, del=DEL, patch=PATCH
} http_method;
string http_method_to_str(http_method methode);
typedef enum {
/*####### 1xx - Informational #######*/
/* Indicates an interim response for communicating connection status
* or request progress prior to completing the requested action and
* sending a final response.
*/
Continue = 100, //!< Indicates that the initial part of a request has been received and has not yet been rejected by the server.
SwitchingProtocols = 101, //!< Indicates that the server understands and is willing to comply with the client's request, via the Upgrade header field, for a change in the application protocol being used on this connection.
Processing = 102, //!< Is an interim response used to inform the client that the server has accepted the complete request, but has not yet completed it.
EarlyHints = 103, //!< Indicates to the client that the server is likely to send a final response with the header fields included in the informational response.
/*####### 2xx - Successful #######*/
/* Indicates that the client's request was successfully received,
* understood, and accepted.
*/
OK = 200, //!< Indicates that the request has succeeded.
Created = 201, //!< Indicates that the request has been fulfilled and has resulted in one or more new resources being created.
Accepted = 202, //!< Indicates that the request has been accepted for processing, but the processing has not been completed.
NonAuthoritativeInformation = 203, //!< Indicates that the request was successful but the enclosed payload has been modified from that of the origin server's 200 (OK) response by a transforming proxy.
NoContent = 204, //!< Indicates that the server has successfully fulfilled the request and that there is no additional content to send in the response payload body.
ResetContent = 205, //!< Indicates that the server has fulfilled the request and desires that the user agent reset the \"document view\", which caused the request to be sent, to its original state as received from the origin server.
PartialContent = 206, //!< Indicates that the server is successfully fulfilling a range request for the target resource by transferring one or more parts of the selected representation that correspond to the satisfiable ranges found in the requests's Range header field.
MultiStatus = 207, //!< Provides status for multiple independent operations.
AlreadyReported = 208, //!< Used inside a DAV:propstat response element to avoid enumerating the internal members of multiple bindings to the same collection repeatedly. [RFC 5842]
IMUsed = 226, //!< The server has fulfilled a GET request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance.
/*####### 3xx - Redirection #######*/
/* Indicates that further action needs to be taken by the user agent
* in order to fulfill the request.
*/
MultipleChoices = 300, //!< Indicates that the target resource has more than one representation, each with its own more specific identifier, and information about the alternatives is being provided so that the user (or user agent) can select a preferred representation by redirecting its request to one or more of those identifiers.
MovedPermanently = 301, //!< Indicates that the target resource has been assigned a new permanent URI and any future references to this resource ought to use one of the enclosed URIs.
Found = 302, //!< Indicates that the target resource resides temporarily under a different URI.
SeeOther = 303, //!< Indicates that the server is redirecting the user agent to a different resource, as indicated by a URI in the Location header field, that is intended to provide an indirect response to the original request.
NotModified = 304, //!< Indicates that a conditional GET request has been received and would have resulted in a 200 (OK) response if it were not for the fact that the condition has evaluated to false.
UseProxy = 305, //!< \deprecated \parblock Due to security concerns regarding in-band configuration of a proxy. \endparblock
//!< The requested resource MUST be accessed through the proxy given by the Location field.
TemporaryRedirect = 307, //!< Indicates that the target resource resides temporarily under a different URI and the user agent MUST NOT change the request method if it performs an automatic redirection to that URI.
PermanentRedirect = 308, //!< The target resource has been assigned a new permanent URI and any future references to this resource outght to use one of the enclosed URIs. [...] This status code is similar to 301 Moved Permanently (Section 7.3.2 of rfc7231), except that it does not allow rewriting the request method from POST to GET.
/*####### 4xx - Client Error #######*/
/* Indicates that the client seems to have erred.
*/
BadRequest = 400, //!< Indicates that the server cannot or will not process the request because the received syntax is invalid, nonsensical, or exceeds some limitation on what the server is willing to process.
Unauthorized = 401, //!< Indicates that the request has not been applied because it lacks valid authentication credentials for the target resource.
PaymentRequired = 402, //!< *Reserved*
Forbidden = 403, //!< Indicates that the server understood the request but refuses to authorize it.
NotFound = 404, //!< Indicates that the origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
MethodNotAllowed = 405, //!< Indicates that the method specified in the request-line is known by the origin server but not supported by the target resource.
NotAcceptable = 406, //!< Indicates that the target resource does not have a current representation that would be acceptable to the user agent, according to the proactive negotiation header fields received in the request, and the server is unwilling to supply a default representation.
ProxyAuthenticationRequired = 407, //!< Is similar to 401 (Unauthorized), but indicates that the client needs to authenticate itself in order to use a proxy.
RequestTimeout = 408, //!< Indicates that the server did not receive a complete request message within the time that it was prepared to wait.
Conflict = 409, //!< Indicates that the request could not be completed due to a conflict with the current state of the resource.
Gone = 410, //!< Indicates that access to the target resource is no longer available at the origin server and that this condition is likely to be permanent.
LengthRequired = 411, //!< Indicates that the server refuses to accept the request without a defined Content-Length.
PreconditionFailed = 412, //!< Indicates that one or more preconditions given in the request header fields evaluated to false when tested on the server.
ContentTooLarge = 413, //!< Indicates that the server is refusing to process a request because the request payload is larger than the server is willing or able to process.
PayloadTooLarge = 413, //!< Alias for ContentTooLarge for backward compatibility.
URITooLong = 414, //!< Indicates that the server is refusing to service the request because the request-target is longer than the server is willing to interpret.
UnsupportedMediaType = 415, //!< Indicates that the origin server is refusing to service the request because the payload is in a format not supported by the target resource for this method.
RangeNotSatisfiable = 416, //!< Indicates that none of the ranges in the request's Range header field overlap the current extent of the selected resource or that the set of ranges requested has been rejected due to invalid ranges or an excessive request of small or overlapping ranges.
ExpectationFailed = 417, //!< Indicates that the expectation given in the request's Expect header field could not be met by at least one of the inbound servers.
ImATeapot = 418, //!< Any attempt to brew coffee with a teapot should result in the error code 418 I'm a teapot.
MisdirectedRequest = 421, //!< Indicates that the request was directed at a server that is unable or unwilling to produce an authoritative response for the target URI.
UnprocessableContent = 422, //!< Means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions.
UnprocessableEntity = 422, //!< Alias for UnprocessableContent for backward compatibility.
Locked = 423, //!< Means the source or destination resource of a method is locked.
FailedDependency = 424, //!< Means that the method could not be performed on the resource because the requested action depended on another action and that action failed.
TooEarly = 425, //!< Indicates that the server is unwilling to risk processing a request that might be replayed.
UpgradeRequired = 426, //!< Indicates that the server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol.
PreconditionRequired = 428, //!< Indicates that the origin server requires the request to be conditional.
TooManyRequests = 429, //!< Indicates that the user has sent too many requests in a given amount of time (\"rate limiting\").
RequestHeaderFieldsTooLarge = 431, //!< Indicates that the server is unwilling to process the request because its header fields are too large.
UnavailableForLegalReasons = 451, //!< This status code indicates that the server is denying access to the resource in response to a legal demand.
/*####### 5xx - Server Error #######*/
/* Indicates that the server is aware that it has erred
* or is incapable of performing the requested method.
*/
InternalServerError = 500, //!< Indicates that the server encountered an unexpected condition that prevented it from fulfilling the request.
NotImplemented = 501, //!< Indicates that the server does not support the functionality required to fulfill the request.
BadGateway = 502, //!< Indicates that the server, while acting as a gateway or proxy, received an invalid response from an inbound server it accessed while attempting to fulfill the request.
ServiceUnavailable = 503, //!< Indicates that the server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay.
GatewayTimeout = 504, //!< Indicates that the server, while acting as a gateway or proxy, did not receive a timely response from an upstream server it needed to access in order to complete the request.
HTTPVersionNotSupported = 505, //!< Indicates that the server does not support, or refuses to support, the protocol version that was used in the request message.
VariantAlsoNegotiates = 506, //!< Indicates that the server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process.
InsufficientStorage = 507, //!< Means the method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request.
LoopDetected = 508, //!< Indicates that the server terminated an operation because it encountered an infinite loop while processing a request with "Depth: infinity". [RFC 5842]
NotExtended = 510, //!< \deprecated \parblock Obsoleted as the experiment has ended and there is no evidence of widespread use. \endparblock
//!< The policy for accessing the resource has not been met in the request. [RFC 2774]
NetworkAuthenticationRequired = 511, //!< Indicates that the client needs to authenticate to gain network access.
xxx_max = 1023
} http_response_code;
string http_response_code_txt(unsigned int code);
}
#endif

@ -5,16 +5,19 @@
#include <string>
#include <map>
#include "elementary.hpp"
#include "api.hpp"
using namespace std;
namespace marcelb {
using namespace std;
class defapi;
class api;
class http_request {
public:
string protocol;
string method;
string url;
map<string, string> headers;
@ -23,22 +26,25 @@ class http_request {
// konstruktori zahtjeva
// odlazni
http_request(const string _method, const string _url, const string _body = "");
http_request(const api *_api);
http_request(const http_method _method, const string _url, const string _body = "", const string _protocol = "1.1");
http_request(const api *_api, const string _protocol = "1.1");
//dolazni
http_request(const string _raw);
//bool validate();
void putheader(const string _key, const string _value);
void setheaders(const map<string, string> _headers);
void header(const string _key, const string _value);
void header(const map<string, string> _headers);
private:
void parse();
void mold();
};
static string get_protocol(const string _protocol);
class http_response {
public:
string protocol;
string status;
map<string, string> headers;
string body;
@ -46,16 +52,21 @@ class http_response {
//konstruktor odgovora
// odlazni
void send(const string _body);
http_response(const http_response_code _status, const string _body = "", const string _protocol = "1.1");
// dolaznih
void get(const string _raw);
http_response(const string _raw);
//bool validate();
// void putheader(const string _key, const string _value);
// void putheaders(const map<string, string> _headers);
void header(const string _key, const string _value);
void header(const map<string, string> _headers);
private:
void mold(); // za slanje
void parse(); // čitaj http
};
static string set_protcol(const string _protocol);
}
#endif

@ -1,18 +1,7 @@
#include "../lib/api.hpp"
defapi::defapi(const vector<string> _methods, const vector<string> _paths, const vector<string> _keys) {
methods = _methods;
paths = _paths;
keys = _keys;
}
void defapi::necessary(const string _path, const vector<string> _keys) {
val_matrix[_path].insert( val_matrix[_path].end(), _keys.begin(), _keys.end());
}
api::api(defapi* _def, const string _method, const string _path, const map<string, string> _params, const string _body) {
def = _def;
method = _method;
marcelb::api::api(const http_method _method, const string _path, const map<string, string> _params, const string _body) {
method = http_method_to_str(_method);
path = _path;
url = path;
@ -26,13 +15,9 @@ api::api(defapi* _def, const string _method, const string _path, const map<strin
body = _body;
// if (!validate()) {
// throw string("[ERROR] The API is not correct ");
// }
}
api::api(defapi* _def, const http_request _req) {
def = _def;
marcelb::api::api(const http_request _req) {
method = _req.method;
//path = _path;
url = _req.url;
@ -56,27 +41,4 @@ api::api(defapi* _def, const http_request _req) {
body = _req.body;
// if (!validate()) {
// cout << "Nije ispravan API" << endl;
// }
}
// bool api::validate() {
// bool isValidate = true;
// cout << "Validiramo " << endl;
// // api validacija ključeva
// for (uint i=0; i<def->val_matrix[path].size(); i++) {
// cout << def->val_matrix[path][i] << " " << params[def->val_matrix[path][i]] << endl;
// if (params[def->val_matrix[path][i]].empty()) {
// cout << "Ptazan " << endl;
// isValidate = false;
// break;
// }
// }
// return isValidate;
// }
}

@ -0,0 +1,108 @@
#include "../lib/elementary.hpp"
string marcelb::http_method_to_str(http_method methode) {
string methode_str;
switch (methode) {
case 0:
methode_str = "GET";
break;
case 1:
methode_str = "POST";
break;
case 2:
methode_str = "PUT";
break;
case 3:
methode_str = "DELETE";
break;
case 4:
methode_str = "PATCH";
break;
default:
throw string("[ERROR] Bad HTTP REST method ");
break;
}
return methode_str;
};
string marcelb::http_response_code_txt(unsigned int code) {
switch (code) {
//####### 1xx - Informational #######
case 100: return "Continue";
case 101: return "Switching Protocols";
case 102: return "Processing";
case 103: return "Early Hints";
//####### 2xx - Successful #######
case 200: return "OK";
case 201: return "Created";
case 202: return "Accepted";
case 203: return "Non-Authoritative Information";
case 204: return "No Content";
case 205: return "Reset Content";
case 206: return "Partial Content";
case 207: return "Multi-Status";
case 208: return "Already Reported";
case 226: return "IM Used";
//####### 3xx - Redirection #######
case 300: return "Multiple Choices";
case 301: return "Moved Permanently";
case 302: return "Found";
case 303: return "See Other";
case 304: return "Not Modified";
case 305: return "Use Proxy";
case 307: return "Temporary Redirect";
case 308: return "Permanent Redirect";
//####### 4xx - Client Error #######
case 400: return "Bad Request";
case 401: return "Unauthorized";
case 402: return "Payment Required";
case 403: return "Forbidden";
case 404: return "Not Found";
case 405: return "Method Not Allowed";
case 406: return "Not Acceptable";
case 407: return "Proxy Authentication Required";
case 408: return "Request Timeout";
case 409: return "Conflict";
case 410: return "Gone";
case 411: return "Length Required";
case 412: return "Precondition Failed";
case 413: return "Content Too Large";
case 414: return "URI Too Long";
case 415: return "Unsupported Media Type";
case 416: return "Range Not Satisfiable";
case 417: return "Expectation Failed";
case 418: return "I'm a teapot";
case 421: return "Misdirected Request";
case 422: return "Unprocessable Content";
case 423: return "Locked";
case 424: return "Failed Dependency";
case 425: return "Too Early";
case 426: return "Upgrade Required";
case 428: return "Precondition Required";
case 429: return "Too Many Requests";
case 431: return "Request Header Fields Too Large";
case 451: return "Unavailable For Legal Reasons";
//####### 5xx - Server Error #######
case 500: return "Internal Server Error";
case 501: return "Not Implemented";
case 502: return "Bad Gateway";
case 503: return "Service Unavailable";
case 504: return "Gateway Timeout";
case 505: return "HTTP Version Not Supported";
case 506: return "Variant Also Negotiates";
case 507: return "Insufficient Storage";
case 508: return "Loop Detected";
case 510: return "Not Extended";
case 511: return "Network Authentication Required";
default: {
throw string("[ERROR] Nonexistent error code ");
}
}
return string();
}

@ -1,25 +1,33 @@
#include "../lib/http.hpp"
http_request::http_request(const string _method, const string _url, const string _body) {
method = _method;
marcelb::http_request::http_request(const http_method _method, const string _url, const string _body, const string _protocol) {
method = http_method_to_str(_method);
url = _url;
body = _body;
protocol = get_protocol(_protocol);
if (!_body.empty()) {
body = _body;
this->header("Content-Length", to_string(body.length()));
}
mold();
}
http_request::http_request(const api *_api) {
marcelb::http_request::http_request(const api *_api, const string _protocol) {
method = _api->method;
url = _api->url;
body = _api->body;
protocol = get_protocol(_protocol);
if (!_api->body.empty()) {
body = _api->body;
this->header("Content-Length", to_string(body.length()));
}
mold();
}
http_request::http_request(const string _raw) {
marcelb::http_request::http_request(const string _raw) {
raw = _raw;
parse();
}
void http_request::parse() {
void marcelb::http_request::parse() {
if (raw.empty()) {
return;
@ -46,12 +54,12 @@ void http_request::parse() {
}
void http_request::putheader(const string _key, const string _value) {
void marcelb::http_request::header(const string _key, const string _value) {
headers[_key] = _value;
mold();
}
void http_request::setheaders(const map<string, string> _headers) {
void marcelb::http_request::header(const map<string, string> _headers) {
headers = _headers;
mold();
}
@ -60,10 +68,10 @@ void http_request::setheaders(const map<string, string> _headers) {
* http zahtjev formiranje raw
*/
void http_request::mold() {
void marcelb::http_request::mold() {
raw = method.empty() ? "GET" : method;
raw += " " + url + " HTTP/1.1\r\n";
raw += " " + url + " " + protocol + "\r\n";
if (!headers.empty()) {
for (auto i : headers) {
@ -74,26 +82,48 @@ void http_request::mold() {
raw += "\r\n" + body;
}
void http_response::send(const string _body) {
body = _body;
marcelb::http_response::http_response(const http_response_code _status, const string _body, const string _protocol) {
status = to_string(_status) + " " + http_response_code_txt(_status);
if (!_body.empty()) {
body = _body;
this->header("Content-Length", to_string(body.length()));
}
protocol = get_protocol(_protocol);
mold();
}
void http_response::get(const string _raw) {
static string marcelb::get_protocol(const string _protocol) {
string protocol;
if (_protocol == "1.0" || _protocol == "1.1" || _protocol == "2.0") {
protocol = "HTTP/" + _protocol;
}
else {
protocol = "HTTP/1.1";
}
return protocol;
}
marcelb::http_response::http_response(const string _raw) {
raw = _raw;
parse();
}
/**
*
*/
void marcelb::http_response::header(const string _key, const string _value) {
headers[_key] = _value;
mold();
}
void marcelb::http_response::header(const map<string, string> _headers) {
headers = _headers;
mold();
}
void http_response::mold() {
raw = "HTTP/1.1 200 OK\r\n"; // implementirati status
void marcelb::http_response::mold() {
raw = protocol + " " + status + "\r\n"; //"HTTP/1.1 200 OK\r\n"; // implementirati status
if (!headers.empty()) {
raw += '?';
for (auto i : headers) {
raw += i.first + ": " + i.second + "\r\n";
}
@ -103,7 +133,7 @@ void http_response::mold() {
}
void http_response::parse() {
void marcelb::http_response::parse() {
if (raw.empty()) {
return;
@ -130,4 +160,15 @@ void http_response::parse() {
else if ((size_t)raw.find("\r\n\r\n") < raw.length())
body = raw.substr(raw.find("\r\n\r\n")+4, raw.find("\r\n")-raw.find("\r\n\r\n")-4);
}
static string marcelb::set_protcol(const string _protocol) {
string protocol;
if (_protocol == "1.0" || _protocol == "1.1" || _protocol == "2.0") {
protocol = "HTTP/" + _protocol;
}
else {
protocol = "HTTP/1.1";
}
return protocol;
}

@ -3,22 +3,35 @@
#include "../lib/api.hpp"
using namespace std;
using namespace marcelb;
int main() {
defapi myApi({"GET"}, {"add", "delete", "update"}, {"id", "key", "value"});
myApi.necessary("add", {"id", "key", "value"});
myApi.necessary("delete", {"id"});
myApi.necessary("update", {"id"});
myApi.necessary("update", {"value"});
try {
api uf(&myApi, "GET", "delete", {make_pair("id", "4")}, "bay");
api uf(GET, "/delete", {make_pair("id", "4")}, "bay");
http_request myreq(&uf);
myreq.header("Content-type", "text/plain");
cout << myreq.raw << endl;
cout << myreq.protocol << endl;
// cout << myreq.status << endl;
for(auto i : myreq.headers)
cout << i.first << " " << i.second << endl;
cout << myreq.body << endl;
} catch (string err) {
http_response myres2(OK, "nnotauth", "1.0" );
cout << myres2.protocol << endl;
cout << myres2.status << endl;
cout << myres2.headers["Content-Length"] << endl;
cout << myres2.body << endl;
} catch (const string err) {
cout << err << endl;
}
// http myHttp(&myApi, "GET /fghfhf HTTP/1.1\r\nBaba");
// //http myHttp(&myApi, "GET /hello/?id=4&post=99 HTTP/1.1\r\nUser-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)\r\nHost: www.tutorialspoint.com\r\nAccept-Language: en-us\r\nAccept-Encoding: gzip, deflate\r\nConnection: Keep-Alive\r\n\r\nHELLO WORLD\r\n");
@ -33,13 +46,13 @@ int main() {
// http_request myres(&uf);
// myres.putheader("Content-type", "text/plain");
http_request myres("GET /delete?id=4 HTTP/1.1\r\nContent-type: text/plain\r\n\n\rBAY");
// http_request myres("GET /delete?id=4 HTTP/1.1\r\nContent-type: text/plain\r\n\n\rBAY");
// myres.get("HTTP/1.1 200 OK\r\n\r\nnotauth");
// myres.get("HTTP/1.1 200 OK");
// myres.header("Content-type", "text/plain");
// api uf(&myApi, myres);

Binary file not shown.
Loading…
Cancel
Save