sa_token_plugin_tide/
adapter.rs1use tide::{Request, Response, StatusCode};
7use sa_token_adapter::{SaRequest, SaResponse, CookieOptions, build_cookie_string};
8use serde::Serialize;
9
10pub struct TideRequestAdapter<'a, State> {
13 request: &'a Request<State>,
14}
15
16impl<'a, State> TideRequestAdapter<'a, State> {
17 pub fn new(request: &'a Request<State>) -> Self {
20 Self { request }
21 }
22}
23
24impl<'a, State> SaRequest for TideRequestAdapter<'a, State> {
25 fn get_header(&self, name: &str) -> Option<String> {
26 self.request
27 .header(name)
28 .and_then(|v| v.as_str().parse().ok())
29 }
30
31 fn get_cookie(&self, name: &str) -> Option<String> {
32 self.request
33 .cookie(name)
34 .map(|c| c.value().to_string())
35 }
36
37 fn get_param(&self, name: &str) -> Option<String> {
38 self.request.url().query_pairs()
39 .find(|(k, _)| k == name)
40 .map(|(_, v)| v.to_string())
41 }
42
43 fn get_path(&self) -> String {
44 self.request.url().path().to_string()
45 }
46
47 fn get_method(&self) -> String {
48 self.request.method().to_string()
49 }
50}
51
52pub struct TideResponseAdapter {
55 response: Response,
56}
57
58impl TideResponseAdapter {
59 pub fn new(response: Response) -> Self {
62 Self { response }
63 }
64
65 pub fn into_response(self) -> Response {
68 self.response
69 }
70}
71
72impl SaResponse for TideResponseAdapter {
73 fn set_header(&mut self, name: &str, value: &str) {
74 self.response.insert_header(name, value);
75 }
76
77 fn set_cookie(&mut self, name: &str, value: &str, options: CookieOptions) {
78 let cookie_string = build_cookie_string(name, value, options);
79 self.set_header("Set-Cookie", &cookie_string);
80 }
81
82 fn set_status(&mut self, status: u16) {
83 let status_code = StatusCode::try_from(status).unwrap_or(StatusCode::Ok);
85 self.response.set_status(status_code);
86 }
87
88 fn set_json_body<U: Serialize>(&mut self, body: U) -> Result<(), serde_json::Error> {
89 match serde_json::to_string(&body) {
90 Ok(json) => {
91 self.response.set_body(json);
92 self.response.set_content_type("application/json");
93 Ok(())
94 }
95 Err(e) => Err(e),
96 }
97 }
98}
99