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
use super::method_not_allowed;
use crate::http::Method;
use crate::{async_trait, Context, Endpoint, Result};
use std::collections::HashSet;
use std::iter::FromIterator;
const ALL_METHODS: [Method; 9] = [
Method::GET,
Method::POST,
Method::PUT,
Method::PATCH,
Method::OPTIONS,
Method::DELETE,
Method::HEAD,
Method::TRACE,
Method::CONNECT,
];
pub struct Guard<E> {
white_list: HashSet<Method>,
endpoint: E,
}
fn hash_set(methods: impl AsRef<[Method]>) -> HashSet<Method> {
HashSet::from_iter(methods.as_ref().to_vec())
}
pub fn allow<E>(methods: impl AsRef<[Method]>, endpoint: E) -> Guard<E> {
Guard {
endpoint,
white_list: hash_set(methods),
}
}
pub fn deny<E>(methods: impl AsRef<[Method]>, endpoint: E) -> Guard<E> {
let white_list = hash_set(ALL_METHODS);
let black_list = &white_list & &hash_set(methods);
Guard {
endpoint,
white_list: &white_list ^ &black_list,
}
}
#[async_trait(?Send)]
impl<'a, S, E> Endpoint<'a, S> for Guard<E>
where
E: Endpoint<'a, S>,
{
#[inline]
async fn call(&'a self, ctx: &'a mut Context<S>) -> Result {
if self.white_list.contains(ctx.method()) {
self.endpoint.call(ctx).await
} else {
method_not_allowed(ctx.method())
}
}
}