-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathbasic_router.hpp
More file actions
1188 lines (1030 loc) · 38.9 KB
/
basic_router.hpp
File metadata and controls
1188 lines (1030 loc) · 38.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright (c) 2025 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/cppalliance/http_proto
//
#ifndef BOOST_HTTP_PROTO_SERVER_BASIC_ROUTER_HPP
#define BOOST_HTTP_PROTO_SERVER_BASIC_ROUTER_HPP
#include <boost/http_proto/detail/config.hpp>
#include <boost/http_proto/detail/type_traits.hpp>
#include <boost/http_proto/server/router_types.hpp>
#include <boost/http_proto/server/route_handler.hpp>
#include <boost/http_proto/method.hpp>
#include <boost/url/url_view.hpp>
#include <boost/capy/detail/call_traits.hpp>
#include <boost/core/detail/string_view.hpp>
#include <boost/core/detail/static_assert.hpp>
#include <type_traits>
namespace boost {
namespace http_proto {
template<class, class>
class basic_router;
/** Configuration options for routers.
*/
struct router_options
{
/** Constructor
Routers constructed with default options inherit the values of
@ref case_sensitive and @ref strict from the parent router.
If there is no parent, both default to `false`.
The value of @ref merge_params always defaults to `false`
and is never inherited.
*/
router_options() = default;
/** Set whether to merge parameters from parent routers.
This setting controls whether route parameters defined on parent
routers are made available in nested routers. It is not inherited
and always defaults to `false`.
@par Example
@code
router r(router_options()
.merge_params(true)
.case_sensitive(true)
.strict(false));
@endcode
@param value `true` to merge parameters from parent routers.
@return A reference to `*this` for chaining.
*/
router_options&
merge_params(
bool value) noexcept
{
v_ = (v_ & ~1) | (value ? 1 : 0);
return *this;
}
/** Set whether pattern matching is case-sensitive.
When this option is not set explicitly, the value is inherited
from the parent router or defaults to `false` if there is no parent.
@par Example
@code
router r(router_options()
.case_sensitive(true)
.strict(true));
@endcode
@param value `true` to perform case-sensitive path matching.
@return A reference to `*this` for chaining.
*/
router_options&
case_sensitive(
bool value) noexcept
{
if(value)
v_ = (v_ & ~6) | 2;
else
v_ = (v_ & ~6) | 4;
return *this;
}
/** Set whether pattern matching is strict.
When this option is not set explicitly, the value is inherited
from the parent router or defaults to `false` if there is no parent.
Strict matching treats a trailing slash as significant:
the pattern `"/api"` matches `"/api"` but not `"/api/"`.
When strict matching is disabled, these paths are treated
as equivalent.
@par Example
@code
router r(router_options()
.strict(true)
.case_sensitive(false));
@endcode
@param value `true` to enable strict path matching.
@return A reference to `*this` for chaining.
*/
router_options&
strict(
bool value) noexcept
{
if(value)
v_ = (v_ & ~24) | 8;
else
v_ = (v_ & ~24) | 16;
return *this;
}
private:
template<class, class> friend class basic_router;
unsigned int v_ = 0;
};
//-----------------------------------------------
//namespace detail {
class any_router;
//-----------------------------------------------
// implementation for all routers
class any_router
{
private:
template<class, class>
friend class http_proto::basic_router;
using opt_flags = unsigned int;
struct BOOST_HTTP_PROTO_DECL any_handler
{
virtual ~any_handler() = default;
virtual std::size_t count() const noexcept = 0;
virtual route_result invoke(
basic_request&, basic_response&) const = 0;
};
using handler_ptr = std::unique_ptr<any_handler>;
struct handler_list
{
std::size_t n;
handler_ptr* p;
};
using match_result = basic_request::match_result;
struct matcher;
struct layer;
struct impl;
BOOST_HTTP_PROTO_DECL ~any_router();
BOOST_HTTP_PROTO_DECL any_router(opt_flags);
BOOST_HTTP_PROTO_DECL any_router(any_router&&) noexcept;
BOOST_HTTP_PROTO_DECL any_router(any_router const&) noexcept;
BOOST_HTTP_PROTO_DECL any_router& operator=(any_router&&) noexcept;
BOOST_HTTP_PROTO_DECL any_router& operator=(any_router const&) noexcept;
BOOST_HTTP_PROTO_DECL std::size_t count() const noexcept;
BOOST_HTTP_PROTO_DECL layer& new_layer(core::string_view pattern);
BOOST_HTTP_PROTO_DECL void add_impl(core::string_view, handler_list const&);
BOOST_HTTP_PROTO_DECL void add_impl(layer&,
http_proto::method, handler_list const&);
BOOST_HTTP_PROTO_DECL void add_impl(layer&,
core::string_view, handler_list const&);
BOOST_HTTP_PROTO_DECL route_result resume_impl(
basic_request&, basic_response&, route_result ec) const;
BOOST_HTTP_PROTO_DECL route_result dispatch_impl(http_proto::method,
core::string_view, urls::url_view const&,
basic_request&, basic_response&) const;
BOOST_HTTP_PROTO_DECL route_result dispatch_impl(
basic_request&, basic_response&) const;
route_result do_dispatch(basic_request&, basic_response&) const;
impl* impl_ = nullptr;
};
//} // detail
//-----------------------------------------------
/** A container for HTTP route handlers.
`basic_router` objects store and dispatch route handlers based on the
HTTP method and path of an incoming request. Routes are added with a
path pattern and an associated handler, and the router is then used to
dispatch the appropriate handler.
Patterns used to create route definitions have percent-decoding applied
when handlers are mounted. A literal "%2F" in the pattern string is
indistinguishable from a literal '/'. For example, "/x%2Fz" is the
same as "/x/z" when used as a pattern.
@par Example
@code
using router_type = basic_router<Req, Res>;
router_type router;
router.get("/hello",
[](Req& req, Res& res)
{
res.status(http_proto::status::ok);
res.set_body("Hello, world!");
return route::send;
});
@endcode
Router objects are lightweight, shared references to their contents.
Copies of a router obtained through construction, conversion, or
assignment do not create new instances; they all refer to the same
underlying data.
@par Handlers
Regular handlers are invoked for matching routes and have this
equivalent signature:
@code
route_result handler( Req& req, Res& res )
@endcode
The return value is a @ref route_result used to indicate the desired
action through @ref route enum values, or to indicate that a failure
occurred. Failures are represented by error codes for which
`system::error_code::failed()` returns `true`.
When a failing error code is produced and remains unhandled, the
router enters error-dispatching mode. In this mode, only error
handlers are invoked. Error handlers are registered globally or
for specific paths and execute in the order of registration whenever
a failing error code is present in the response.
Error handlers have this equivalent signature:
@code
route_result error_handler( Req& req, Res& res, system::error_code ec )
@endcode
Each error handler may return any failing @ref system::error_code,
which is equivalent to calling:
@code
res.next(ec); // with ec.failed() == true
@endcode
Returning @ref route::next indicates that control should proceed to
the next matching error handler. Returning a different failing code
replaces the current error and continues dispatch in error mode using
that new code. Error handlers are invoked until one returns a result
other than @ref route::next.
@par Handler requirements
Regular handlers must be callable with:
@code
route_result( Req&, Res& )
@endcode
Error handlers must be callable with:
@code
route_result( Req&, Res&, system::error_code )
@endcode
Error handlers are invoked only when the response has a failing
error code, and execute in sequence until one returns a result
other than @ref route::next.
The prefix match is not strict: middleware attached to `"/api"`
will also match `"/api/users"` and `"/api/data"`. When registered
before route handlers for the same prefix, middleware runs before
those routes. This is analogous to `app.use(path, ...)` in
Express.js.
@par Thread Safety
Member functions marked `const` such as @ref dispatch and @ref resume
may be called concurrently on routers that refer to the same data.
Modification of routers through calls to non-`const` member functions
is not thread-safe and must not be performed concurrently with any
other member function.
@par Constraints
`Req` must be publicly derived from @ref basic_request.
`Res` must be publicly derived from @ref basic_response.
@tparam Req The type of request object.
@tparam Res The type of response object.
*/
template<class Req, class Res>
class basic_router : public /*detail::*/any_router
{
// Req must be publicly derived from basic_request
BOOST_CORE_STATIC_ASSERT(
detail::derived_from<basic_request, Req>::value);
// Res must be publicly derived from basic_response
BOOST_CORE_STATIC_ASSERT(
detail::derived_from<basic_response, Res>::value);
// 0 = unrecognized
// 1 = normal handler (Req&, Res&)
// 2 = error handler (Req&, Res&, error_code)
// 4 = basic_router<Req, Res>
template<class T, class = void>
struct handler_type
: std::integral_constant<int, 0>
{
};
// route_result( Req&, Res& ) const
template<class T>
struct handler_type<T, typename
std::enable_if<std::is_convertible<
decltype(std::declval<T const&>()(
std::declval<Req&>(),
std::declval<Res&>())),
route_result>::value
>::type> : std::integral_constant<int, 1> {};
// route_result( Req&, Res&, system::error_code const& ) const
template<class T>
struct handler_type<T, typename
std::enable_if<std::is_convertible<
decltype(std::declval<T const&>()(
std::declval<Req&>(),
std::declval<Res&>(),
std::declval<system::error_code const&>())),
route_result>::value
>::type> : std::integral_constant<int, 2> {};
// basic_router<Req, Res>
template<class T>
struct handler_type<T, typename
std::enable_if<
std::is_base_of<any_router, T>::value &&
std::is_convertible<T const volatile*,
any_router const volatile*>::value &&
std::is_constructible<T, basic_router<Req, Res>>::value
>::type> : std::integral_constant<int, 4> {};
template<std::size_t Mask, class... Ts>
struct handler_check : std::true_type {};
template<std::size_t Mask, class T0, class... Ts>
struct handler_check<Mask, T0, Ts...>
: std::conditional<
( (handler_type<T0>::value & Mask) != 0 ),
handler_check<Mask, Ts...>,
std::false_type
>::type {};
template<class H, class = void>
struct except_type : std::false_type {};
template<class H>
struct except_type<H, typename std::enable_if<
capy::detail::call_traits<H>{} && (
capy::detail::type_list_size<typename
capy::detail::call_traits<H>::arg_types>{} == 3) &&
std::is_convertible<Req&, typename capy::detail::type_at<0, typename
capy::detail::call_traits<H>::arg_types>::type>::value &&
std::is_convertible<Res&, typename capy::detail::type_at<1, typename
capy::detail::call_traits<H>::arg_types>::type>{}
>::type>
: std::true_type
{
using type = typename std::decay<typename
capy::detail::type_at<2,typename
capy::detail::call_traits<H>::arg_types>::type>::type;
};
template<int, class... Hs>
struct except_types;
template<int N>
struct except_types<N> : std::true_type {};
template<int N, class H1, class... HN>
struct except_types<N, H1, HN...> : std::integral_constant<bool,
except_type<H1>{} && except_types<N, HN...>{}>
{};
public:
/** The type of request object used in handlers
*/
using request_type = Req;
/** The type of response object used in handlers
*/
using response_type = Res;
/** A fluent interface for defining handlers on a specific route.
This type represents a single route within the router and
provides a chainable API for registering handlers associated
with particular HTTP methods or for all methods collectively.
Typical usage registers one or more handlers for a route:
@code
router.route("/users/:id")
.get(show_user)
.put(update_user)
.all(log_access);
@endcode
Each call appends handlers in registration order.
*/
class fluent_route;
/** Constructor
Creates an empty router with the specified configuration.
Routers constructed with default options inherit the values
of @ref router_options::case_sensitive and
@ref router_options::strict from the parent router, or default
to `false` if there is no parent. The value of
@ref router_options::merge_params defaults to `false` and
is never inherited.
@param options The configuration options to use.
*/
explicit
basic_router(router_options options = {})
: any_router(options.v_)
{
}
/** Construct a router from another router with compatible types.
This constructs a router that shares the same underlying routing
state as another router whose request and response types are base
classes of `Req` and `Res`, respectively.
The resulting router participates in shared ownership of the
implementation; copying the router does not duplicate routes or
handlers, and changes visible through one router are visible
through all routers that share the same underlying state.
@par Constraints
`Req` must be derived from `OtherReq`, and `Res` must be
derived from `OtherRes`.
@tparam OtherReq The request type of the source router.
@tparam OtherRes The response type of the source router.
@param other The router to copy.
*/
template<
class OtherReq, class OtherRes,
class = typename std::enable_if<
detail::derived_from<Req, OtherReq>::value &&
detail::derived_from<Res, OtherRes>::value>::type
>
basic_router(
basic_router<OtherReq, OtherRes> const& other)
: any_router(other)
{
}
/** Add one or more middleware handlers for a path prefix.
Each handler registered with this function participates in the
routing and error-dispatch process for requests whose path begins
with the specified prefix, as described in the @ref basic_router
class documentation. Handlers execute in the order they are added
and may return @ref route::next to transfer control to the
subsequent handler in the chain.
@par Example
@code
router.use("/api",
[](Request& req, Response& res)
{
if (!authenticate(req))
{
res.status(401);
res.set_body("Unauthorized");
return route::send;
}
return route::next;
},
[](Request&, Response& res)
{
res.set_header("X-Powered-By", "MyServer");
return route::next;
});
@endcode
@par Preconditions
@p `pattern` must be a valid path prefix; it may be empty to
indicate the root scope.
@param pattern The pattern to match.
@param h1 The first handler to add.
@param hn Additional handlers to add, invoked after @p h1 in
registration order.
*/
template<class H1, class... HN>
void use(
core::string_view pattern,
H1&& h1, HN... hn)
{
// If you get a compile error on this line it means that
// one or more of the provided types is not a valid handler,
// error handler, or router.
BOOST_CORE_STATIC_ASSERT(handler_check<7, H1, HN...>::value);
add_impl(pattern, make_handler_list(
std::forward<H1>(h1), std::forward<HN>(hn)...));
}
/** Add one or more global middleware handlers.
Each handler registered with this function participates in the
routing and error-dispatch process as described in the
@ref basic_router class documentation. Handlers execute in the
order they are added and may return @ref route::next to transfer
control to the next handler in the chain.
This is equivalent to writing:
@code
use( "/", h1, hn... );
@endcode
@par Example
@code
router.use(
[](Request&, Response& res)
{
res.message.erase("X-Powered-By");
return route::next;
});
@endcode
@par Constraints
@li `h1` must not be convertible to @ref core::string_view.
@param h1 The first handler to add.
@param hn Additional handlers to add, invoked after @p h1 in
registration order.
*/
template<class H1, class... HN
, class = typename std::enable_if<
! std::is_convertible<H1, core::string_view>::value>::type>
void use(H1&& h1, HN&&... hn)
{
// If you get a compile error on this line it means that
// one or more of the provided types is not a valid handler,
// error handler, or router.
BOOST_CORE_STATIC_ASSERT(handler_check<7, H1, HN...>::value);
use(core::string_view(),
std::forward<H1>(h1), std::forward<HN>(hn)...);
}
/** Add a global exception handler.
*/
template<class H1, class... HN>
void except(
core::string_view pattern,
H1&& h1, HN... hn)
{
// If you get a compile error on this line it means that one or
// more of the provided types is not a valid exception handler
BOOST_CORE_STATIC_ASSERT(except_types<0, H1, HN...>::value);
add_impl(pattern, make_except_list(
std::forward<H1>(h1), std::forward<HN>(hn)...));
}
template<class H1, class... HN
, class = typename std::enable_if<
! std::is_convertible<H1, core::string_view>::value>::type>
void except(H1&& h1, HN&&... hn)
{
// If you get a compile error on this line it means that one or
// more of the provided types is not a valid exception handler
BOOST_CORE_STATIC_ASSERT(except_types<0, H1, HN...>::value);
except(core::string_view(),
std::forward<H1>(h1), std::forward<HN>(hn)...);
}
/** Add handlers for all HTTP methods matching a path pattern.
This registers regular handlers for the specified path pattern,
participating in dispatch as described in the @ref basic_router
class documentation. Handlers run when the route matches,
regardless of HTTP method, and execute in registration order.
Error handlers and routers cannot be passed here. A new route
object is created even if the pattern already exists.
@code
router.route("/status")
.head(check_headers)
.get(send_status)
.all(log_access);
@endcode
@par Preconditions
@p `pattern` must be a valid path pattern; it must not be empty.
@param pattern The path pattern to match.
@param h1 The first handler to add.
@param hn Additional handlers to add, invoked after @p h1 in
registration order.
*/
template<class H1, class... HN>
void all(
core::string_view pattern,
H1&& h1, HN&&... hn)
{
// If you get a compile error on this line it means that
// one or more of the provided types is not a valid handler.
// Error handlers and routers cannot be passed here.
BOOST_CORE_STATIC_ASSERT(handler_check<1, H1, HN...>::value);
this->route(pattern).all(
std::forward<H1>(h1), std::forward<HN>(hn)...);
}
/** Add one or more route handlers for a method and pattern.
This registers regular handlers for the specified HTTP verb and
path pattern, participating in dispatch as described in the
@ref basic_router class documentation. Error handlers and
routers cannot be passed here.
@param verb The known HTTP method to match.
@param pattern The path pattern to match.
@param h1 The first handler to add.
@param hn Additional handlers to add, invoked after @p h1 in
registration order.
*/
template<class H1, class... HN>
void add(
http_proto::method verb,
core::string_view pattern,
H1&& h1, HN&&... hn)
{
// If you get a compile error on this line it means that
// one or more of the provided types is not a valid handler.
// Error handlers and routers cannot be passed here.
BOOST_CORE_STATIC_ASSERT(handler_check<1, H1, HN...>::value);
this->route(pattern).add(verb,
std::forward<H1>(h1), std::forward<HN>(hn)...);
}
/** Add one or more route handlers for a method and pattern.
This registers regular handlers for the specified HTTP verb and
path pattern, participating in dispatch as described in the
@ref basic_router class documentation. Error handlers and
routers cannot be passed here.
@param verb The HTTP method string to match.
@param pattern The path pattern to match.
@param h1 The first handler to add.
@param hn Additional handlers to add, invoked after @p h1 in
registration order.
*/
template<class H1, class... HN>
void add(
core::string_view verb,
core::string_view pattern,
H1&& h1, HN&&... hn)
{
// If you get a compile error on this line it means that
// one or more of the provided types is not a valid handler.
// Error handlers and routers cannot be passed here.
BOOST_CORE_STATIC_ASSERT(handler_check<1, H1, HN...>::value);
this->route(pattern).add(verb,
std::forward<H1>(h1), std::forward<HN>(hn)...);
}
/** Return a fluent route for the specified path pattern.
Adds a new route to the router for the given pattern.
A new route object is always created, even if another
route with the same pattern already exists. The returned
@ref fluent_route reference allows method-specific handler
registration (such as GET or POST) or catch-all handlers
with @ref fluent_route::all.
@param pattern The path expression to match against request
targets. This may include parameters or wildcards following
the router's pattern syntax. May not be empty.
@return A fluent route interface for chaining handler registrations.
*/
auto
route(
core::string_view pattern) -> fluent_route
{
return fluent_route(*this, pattern);
}
//--------------------------------------------
/** Dispatch a request to the appropriate handler.
This runs the routing and error-dispatch logic for the given HTTP
method and target URL, as described in the @ref basic_router class
documentation.
@par Thread Safety
This function may be called concurrently on the same object along
with other `const` member functions. Each concurrent invocation
must use distinct request and response objects.
@param verb The HTTP method to match. This must not be
@ref http_proto::method::unknown.
@param url The full request target used for route matching.
@param req The request to pass to handlers.
@param res The response to pass to handlers.
@return The @ref route_result describing how routing completed.
@throws std::invalid_argument If @p verb is
@ref http_proto::method::unknown.
*/
auto
dispatch(
http_proto::method verb,
urls::url_view const& url,
Req& req, Res& res) const ->
route_result
{
if(verb == http_proto::method::unknown)
detail::throw_invalid_argument();
return dispatch_impl(verb,
core::string_view(), url, req, res);
}
/** Dispatch a request to the appropriate handler using a method string.
This runs the routing and error-dispatch logic for the given HTTP
method string and target URL, as described in the @ref basic_router
class documentation. This overload is intended for method tokens
that are not represented by @ref http_proto::method.
@par Thread Safety
This function may be called concurrently on the same object along
with other `const` member functions. Each concurrent invocation
must use distinct request and response objects.
@param verb The HTTP method string to match. This must not be empty.
@param url The full request target used for route matching.
@param req The request to pass to handlers.
@param res The response to pass to handlers.
@return The @ref route_result describing how routing completed.
@throws std::invalid_argument If @p verb is empty.
*/
auto
dispatch(
core::string_view verb,
urls::url_view const& url,
Req& req, Res& res) ->
route_result
{
// verb cannot be empty
if(verb.empty())
detail::throw_invalid_argument();
return dispatch_impl(
http_proto::method::unknown,
verb, url, req, res);
}
/** Resume dispatch after a detached handler.
This continues routing after a previous call to @ref dispatch
returned @ref route::detach. It recreates the routing state and
resumes as if the handler that detached had instead returned
the specified @p ec from its body. The regular routing and
error-dispatch logic then proceeds as described in the
@ref basic_router class documentation. For example, if @p ec is
@ref route::next, the next matching handlers are invoked.
@par Thread Safety
This function may be called concurrently on the same object along
with other `const` member functions. Each concurrent invocation
must use distinct request and response objects.
@param req The request to pass to handlers.
@param res The response to pass to handlers.
@param rv The @ref route_result to resume with, as if returned
by the detached handler.
@return The @ref route_result describing how routing completed.
*/
auto
resume(
Req& req, Res& res,
route_result const& rv) const ->
route_result
{
return resume_impl(req, res, rv);
}
private:
struct undo_resume
{
std::size_t& resume;
bool undo_ = true;
~undo_resume()
{
if(undo_)
resume = 0;
}
undo_resume(
std::size_t& resume_) noexcept
: resume(resume_)
{
}
void cancel() noexcept
{
undo_ = false;
}
};
// wrapper for route handlers
template<
class H,
class Ty = handler_type<typename
std::decay<H>::type > >
struct handler_impl : any_handler
{
typename std::decay<H>::type h;
template<class... Args>
explicit handler_impl(Args&&... args)
: h(std::forward<Args>(args)...)
{
}
std::size_t
count() const noexcept override
{
return count(Ty{});
}
route_result
invoke(
basic_request& req,
basic_response& res) const override
{
return invoke(
static_cast<Req&>(req),
static_cast<Res&>(res), Ty{});
}
private:
std::size_t count(
std::integral_constant<int, 0>) = delete;
std::size_t count(
std::integral_constant<int, 1>) const noexcept
{
return 1;
}
std::size_t count(
std::integral_constant<int, 2>) const noexcept
{
return 1;
}
std::size_t count(
std::integral_constant<int, 4>) const noexcept
{
return 1 + h.count();
}
route_result invoke(Req&, Res&,
std::integral_constant<int, 0>) const = delete;
// (Req, Res)
route_result invoke(Req& req, Res& res,
std::integral_constant<int, 1>) const
{
auto& res_ = static_cast<
basic_response&>(res);
if( res_.ec_.failed() ||
res_.ep_)
return http_proto::route::next;
// avoid racing on res_.resume_
undo_resume u(res_.resume_);
res_.resume_ = res_.pos_;
auto rv = h(req, res);
if(rv == http_proto::route::detach)
{
u.cancel();
return rv;
}
return rv;
}
// (Req&, Res&, error_code)
route_result
invoke(Req& req, Res& res,
std::integral_constant<int, 2>) const
{
auto& res_ = static_cast<
basic_response&>(res);
if(! res_.ec_.failed())
return http_proto::route::next;
// avoid racing on res.resume_
res_.resume_ = res_.pos_;
undo_resume u(res_.resume_);
auto rv = h(req, res, res_.ec_);
if(rv == http_proto::route::detach)
{
u.cancel();
return rv;
}
return rv;
}
// any_router
route_result invoke(Req& req, Res& res,
std::integral_constant<int, 4>) const
{
auto const& res_ = static_cast<
basic_response const&>(res);
if( res_.resume_ > 0 ||
( ! res_.ec_.failed() &&
! res_.ep_))
return h.dispatch_impl(req, res);
return http_proto::route::next;
}
};
template<class H, class E = typename
except_type<typename std::decay<H>::type>::type>
struct except_impl : any_handler
{
typename std::decay<H>::type h;
template<class... Args>
explicit except_impl(Args&&... args)
: h(std::forward<Args>(args)...)
{
}
std::size_t
count() const noexcept override
{
return 1;
}
route_result
invoke(Req& req, Res& res) const override
{
#ifndef BOOST_NO_EXCEPTIONS
auto& res_ = static_cast<
basic_response&>(res);
if( ! res_.ec_.failed() &&
! res_.ep_)
return http_proto::route::next;
volatile int dummy = sizeof(E);
(void)(dummy);
try
{
std::rethrow_exception(res_.ep_);
}
catch(E const& ex)
{
// avoid racing on res.resume_
res_.resume_ = res_.pos_;
undo_resume u(res_.resume_);
// VFALCO What if h throws?
auto rv = h(req, res, ex);
if(rv == http_proto::route::detach)
{
u.cancel();
return rv;
}
return rv;
}
catch(...)
{
res_.ep_ = std::current_exception();
return http_proto::route::next;
}
#else
(void)req;
(void)res;
return http_proto::route::next;
#endif
}
};
template<std::size_t N>
struct handler_list_impl : handler_list
{
template<class... HN>
explicit handler_list_impl(HN&&... hn)
{
n = sizeof...(HN);
p = v;
assign<0>(std::forward<HN>(hn)...);
}
// exception handlers