Line data Source code
1 : //
2 : // Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
3 : //
4 : // Distributed under the Boost Software License, Version 1.0. (See accompanying
5 : // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6 : //
7 : // Official repository: https://github.com/cppalliance/http
8 : //
9 :
10 : #ifndef BOOST_HTTP_SERVER_CORS_HPP
11 : #define BOOST_HTTP_SERVER_CORS_HPP
12 :
13 : #include <boost/http/detail/config.hpp>
14 : #include <boost/http/server/route_handler.hpp>
15 : #include <boost/http/status.hpp>
16 : #include <chrono>
17 :
18 : namespace boost {
19 : namespace http {
20 :
21 : /** Options for CORS middleware configuration.
22 : */
23 : struct cors_options
24 : {
25 : /// Allowed origin, or "*" for any. Empty defaults to "*".
26 : std::string origin;
27 :
28 : /// Allowed HTTP methods. Empty defaults to common methods.
29 : std::string methods;
30 :
31 : /// Allowed request headers.
32 : std::string allowedHeaders;
33 :
34 : /// Response headers exposed to client.
35 : std::string exposedHeaders;
36 :
37 : /// Max age for preflight cache.
38 5 : std::chrono::seconds max_age{ 0 };
39 :
40 : /// Status code for preflight response.
41 : status result = status::no_content;
42 :
43 : /// If true, pass preflight to next handler.
44 : bool preFlightContinue = false;
45 :
46 : /// If true, allow credentials.
47 : bool credentials = false;
48 : };
49 :
50 : /** CORS middleware for handling cross-origin requests.
51 :
52 : This middleware handles Cross-Origin Resource Sharing
53 : (CORS) by setting appropriate response headers and
54 : handling preflight OPTIONS requests.
55 :
56 : @par Example
57 : @code
58 : cors_options opts;
59 : opts.origin = "*";
60 : opts.methods = "GET,POST,PUT,DELETE";
61 : opts.credentials = true;
62 :
63 : router.use( cors( opts ) );
64 : @endcode
65 :
66 : @see cors_options
67 : */
68 : class BOOST_HTTP_DECL cors
69 : {
70 : cors_options options_;
71 :
72 : public:
73 : /** Construct a CORS middleware.
74 :
75 : @param options Configuration options.
76 : */
77 : explicit cors(cors_options options = {}) noexcept;
78 :
79 : /** Handle a request.
80 :
81 : Sets CORS headers and handles preflight requests.
82 :
83 : @param rp The route parameters.
84 :
85 : @return A task that completes with the routing result.
86 : */
87 : route_task operator()(route_params& rp) const;
88 : };
89 :
90 : } // http
91 : } // boost
92 :
93 : #endif
|