Skip to main content

aiway_protocol/context/
request_context.rs

1use crate::SV;
2use crate::context::route::Route;
3use bytes::Bytes;
4use dashmap::DashMap;
5use std::sync::Arc;
6
7/// 请求上下文
8#[derive(Debug, Default)]
9pub struct RequestContext {
10    /// 请求ID
11    pub request_id: String,
12    /// 收到请求的时间戳,毫秒
13    pub request_ts: i64,
14    /// 请求方法:`GET` | `POST` | `PUT` | `DELETE` | `PATCH` | `OPTIONS` | `HEAD`
15    pub method: SV<String>,
16    /// Host
17    pub host: String,
18    /// 请求路径,不含参数。
19    pub path: SV<String>,
20    /// 请求头
21    pub headers: DashMap<String, String>,
22    /// 请求的Query参数
23    pub query: DashMap<String, String>,
24    /// 请求体
25    pub body: SV<Bytes>,
26    /// 路由配置信息
27    pub route: SV<Arc<Route>>,
28    /// 路由目标地址,可以是域名或IP(包含协议头),由负载均衡器设置
29    pub routing_url: SV<String>,
30}
31
32impl RequestContext {
33    pub fn get_request_ts(&self) -> i64 {
34        self.request_ts
35    }
36
37    pub fn get_host(&self) -> &str {
38        &self.host
39    }
40    pub fn get_method(&self) -> Option<&str> {
41        self.method.get().map(|s| s.as_str())
42    }
43    pub fn set_path(&self, path: &str) {
44        self.path.set(path.to_string());
45    }
46
47    pub fn get_path(&self) -> String {
48        self.path.get().cloned().unwrap_or_default()
49    }
50
51    pub fn insert_header(&self, key: &str, value: &str) {
52        self.headers.insert(key.to_string(), value.to_string());
53    }
54
55    pub fn get_header(&self, key: &str) -> Option<String> {
56        self.headers.get(key).map(|v| v.value().clone())
57    }
58
59    pub fn remove_header(&self, key: &str) {
60        self.headers.remove(key);
61    }
62
63    pub fn insert_query(&self, name: &str, value: &str) {
64        self.query.insert(name.to_string(), value.to_string());
65    }
66
67    pub fn get_query(&self, name: &str) -> Option<String> {
68        self.query.get(name).map(|v| v.value().clone())
69    }
70
71    pub fn set_body(&self, body: Bytes) {
72        self.body.set(body)
73    }
74
75    pub fn get_body(&self) -> Option<&Bytes> {
76        self.body.get()
77    }
78
79    pub fn set_route(&self, route: Arc<Route>) {
80        self.route.set(route);
81    }
82
83    pub fn get_route(&self) -> Option<&Arc<Route>> {
84        self.route.get()
85    }
86
87    pub fn set_routing_url(&self, url: String) {
88        self.routing_url.set(url);
89    }
90
91    pub fn get_routing_url(&self) -> Option<&String> {
92        self.routing_url.get()
93    }
94
95}