HttpRequest.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/ByteBuffer.h>
  9. #include <AK/DeprecatedString.h>
  10. #include <AK/Optional.h>
  11. #include <AK/URL.h>
  12. #include <AK/Vector.h>
  13. #include <LibCore/Forward.h>
  14. namespace HTTP {
  15. class HttpRequest {
  16. public:
  17. enum class ParseError {
  18. RequestTooLarge,
  19. RequestIncomplete,
  20. OutOfMemory,
  21. UnsupportedMethod
  22. };
  23. static StringView parse_error_to_string(ParseError error)
  24. {
  25. switch (error) {
  26. case ParseError::RequestTooLarge:
  27. return "Request too large"sv;
  28. case ParseError::RequestIncomplete:
  29. return "Request is incomplete"sv;
  30. case ParseError::OutOfMemory:
  31. return "Out of memory"sv;
  32. case ParseError::UnsupportedMethod:
  33. return "Unsupported method"sv;
  34. default:
  35. VERIFY_NOT_REACHED();
  36. }
  37. }
  38. enum Method {
  39. Invalid,
  40. HEAD,
  41. GET,
  42. POST,
  43. DELETE,
  44. PATCH,
  45. OPTIONS,
  46. TRACE,
  47. CONNECT,
  48. PUT,
  49. };
  50. struct Header {
  51. DeprecatedString name;
  52. DeprecatedString value;
  53. };
  54. struct BasicAuthenticationCredentials {
  55. DeprecatedString username;
  56. DeprecatedString password;
  57. };
  58. HttpRequest() = default;
  59. ~HttpRequest() = default;
  60. DeprecatedString const& resource() const { return m_resource; }
  61. Vector<Header> const& headers() const { return m_headers; }
  62. URL const& url() const { return m_url; }
  63. void set_url(URL const& url) { m_url = url; }
  64. Method method() const { return m_method; }
  65. void set_method(Method method) { m_method = method; }
  66. ByteBuffer const& body() const { return m_body; }
  67. void set_body(ByteBuffer&& body) { m_body = move(body); }
  68. DeprecatedString method_name() const;
  69. ErrorOr<ByteBuffer> to_raw_request() const;
  70. void set_headers(HashMap<DeprecatedString, DeprecatedString> const&);
  71. static ErrorOr<HttpRequest, HttpRequest::ParseError> from_raw_request(ReadonlyBytes);
  72. static Optional<Header> get_http_basic_authentication_header(URL const&);
  73. static Optional<BasicAuthenticationCredentials> parse_http_basic_authentication_header(DeprecatedString const&);
  74. private:
  75. URL m_url;
  76. DeprecatedString m_resource;
  77. Method m_method { GET };
  78. Vector<Header> m_headers;
  79. ByteBuffer m_body;
  80. };
  81. DeprecatedString to_deprecated_string(HttpRequest::Method);
  82. }