http.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #pragma once
  2. #include <cpp-httplib/httplib.h>
  3. struct common_http_url {
  4. std::string scheme;
  5. std::string user;
  6. std::string password;
  7. std::string host;
  8. std::string path;
  9. };
  10. static common_http_url common_http_parse_url(const std::string & url) {
  11. common_http_url parts;
  12. auto scheme_end = url.find("://");
  13. if (scheme_end == std::string::npos) {
  14. throw std::runtime_error("invalid URL: no scheme");
  15. }
  16. parts.scheme = url.substr(0, scheme_end);
  17. if (parts.scheme != "http" && parts.scheme != "https") {
  18. throw std::runtime_error("unsupported URL scheme: " + parts.scheme);
  19. }
  20. auto rest = url.substr(scheme_end + 3);
  21. auto at_pos = rest.find('@');
  22. if (at_pos != std::string::npos) {
  23. auto auth = rest.substr(0, at_pos);
  24. auto colon_pos = auth.find(':');
  25. if (colon_pos != std::string::npos) {
  26. parts.user = auth.substr(0, colon_pos);
  27. parts.password = auth.substr(colon_pos + 1);
  28. } else {
  29. parts.user = auth;
  30. }
  31. rest = rest.substr(at_pos + 1);
  32. }
  33. auto slash_pos = rest.find('/');
  34. if (slash_pos != std::string::npos) {
  35. parts.host = rest.substr(0, slash_pos);
  36. parts.path = rest.substr(slash_pos);
  37. } else {
  38. parts.host = rest;
  39. parts.path = "/";
  40. }
  41. return parts;
  42. }
  43. static std::pair<httplib::Client, common_http_url> common_http_client(const std::string & url) {
  44. common_http_url parts = common_http_parse_url(url);
  45. if (parts.host.empty()) {
  46. throw std::runtime_error("error: invalid URL format");
  47. }
  48. httplib::Client cli(parts.scheme + "://" + parts.host);
  49. if (!parts.user.empty()) {
  50. cli.set_basic_auth(parts.user, parts.password);
  51. }
  52. cli.set_follow_location(true);
  53. return { std::move(cli), std::move(parts) };
  54. }
  55. static std::string common_http_show_masked_url(const common_http_url & parts) {
  56. return parts.scheme + "://" + (parts.user.empty() ? "" : "****:****@") + parts.host + parts.path;
  57. }