HttpRequest.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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/ByteString.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. InvalidURL
  23. };
  24. static StringView parse_error_to_string(ParseError error)
  25. {
  26. switch (error) {
  27. case ParseError::RequestTooLarge:
  28. return "Request too large"sv;
  29. case ParseError::RequestIncomplete:
  30. return "Request is incomplete"sv;
  31. case ParseError::OutOfMemory:
  32. return "Out of memory"sv;
  33. case ParseError::UnsupportedMethod:
  34. return "Unsupported method"sv;
  35. default:
  36. VERIFY_NOT_REACHED();
  37. }
  38. }
  39. enum Method {
  40. Invalid,
  41. HEAD,
  42. GET,
  43. POST,
  44. DELETE,
  45. PATCH,
  46. OPTIONS,
  47. TRACE,
  48. CONNECT,
  49. PUT,
  50. };
  51. struct Header {
  52. ByteString name;
  53. ByteString value;
  54. };
  55. struct BasicAuthenticationCredentials {
  56. ByteString username;
  57. ByteString password;
  58. };
  59. HttpRequest() = default;
  60. ~HttpRequest() = default;
  61. ByteString const& resource() const { return m_resource; }
  62. Vector<Header> const& headers() const { return m_headers; }
  63. URL const& url() const { return m_url; }
  64. void set_url(URL const& url) { m_url = url; }
  65. Method method() const { return m_method; }
  66. void set_method(Method method) { m_method = method; }
  67. ByteBuffer const& body() const { return m_body; }
  68. void set_body(ByteBuffer&& body) { m_body = move(body); }
  69. StringView method_name() const;
  70. ErrorOr<ByteBuffer> to_raw_request() const;
  71. void set_headers(HashMap<ByteString, ByteString> const&);
  72. static ErrorOr<HttpRequest, HttpRequest::ParseError> from_raw_request(ReadonlyBytes);
  73. static Optional<Header> get_http_basic_authentication_header(URL const&);
  74. static Optional<BasicAuthenticationCredentials> parse_http_basic_authentication_header(ByteString const&);
  75. private:
  76. URL m_url;
  77. ByteString m_resource;
  78. Method m_method { GET };
  79. Vector<Header> m_headers;
  80. ByteBuffer m_body;
  81. };
  82. StringView to_string_view(HttpRequest::Method);
  83. }