dzgt_utils/
http_util.rs

1#![allow(unused)]
2
3use std::fmt::{Debug, Formatter};
4use std::sync::Arc;
5use std::time::Duration;
6use cyfs_base::*;
7pub use sfo_http::http_util::header::{HeaderName, HeaderValue};
8use sfo_http::http_util::JsonValue;
9use tide::convert::{Deserialize, Serialize};
10use tide::{Response, StatusCode};
11use crate::into_bucky_err;
12use crate::error_util::IntoBuckyError;
13
14pub async fn http_post_request(url: &str, param: Vec<u8>, content_type: Option<&str>) -> BuckyResult<(Vec<u8>, Option<String>)> {
15    sfo_http::http_util::http_post_request(url, param, content_type).await.map_err(into_bucky_err!("request url {} failed", url))
16}
17
18pub async fn http_post_request2<T: for<'de> Deserialize<'de>>(url: &str, param: Vec<u8>, content_type: Option<&str>) -> BuckyResult<T> {
19    sfo_http::http_util::http_post_request2(url, param, content_type).await.map_err(into_bucky_err!("request url {} failed", url))
20}
21
22pub async fn http_post_request3<T: for<'de> Deserialize<'de>, P: Serialize>(url: &str, param: &P) -> BuckyResult<T> {
23    sfo_http::http_util::http_post_request3(url, param).await.map_err(into_bucky_err!("request url {} failed", url))
24}
25
26pub async fn http_get_request2<T: for<'de> Deserialize<'de>>(url: &str) -> BuckyResult<T> {
27    sfo_http::http_util::http_get_request2(url).await.map_err(into_bucky_err!("request url {} failed", url))
28}
29
30
31pub async fn http_get_request(url: &str) -> BuckyResult<(Vec<u8>, Option<String>)> {
32    sfo_http::http_util::http_get_request(url).await.map_err(into_bucky_err!("request url {} failed", url))
33}
34
35pub async fn http_get_request3(url: &str) -> BuckyResult<sfo_http::http_util::Response> {
36    sfo_http::http_util::http_get_request3(url).await.map_err(into_bucky_err!("request url {} failed", url))
37}
38
39pub async fn http_request(req: sfo_http::http_util::Request) -> BuckyResult<sfo_http::http_util::Response> {
40    sfo_http::http_util::http_request(req).await.map_err(into_bucky_err!("request failed"))
41}
42
43pub async fn http_post_json(url: &str, param: JsonValue) -> BuckyResult<JsonValue> {
44    sfo_http::http_util::http_post_json(url, param).await.map_err(into_bucky_err!("request url {} failed", url))
45}
46
47pub async fn http_post_json2<T: for<'de> Deserialize<'de>>(url: &str, param: JsonValue) -> BuckyResult<T> {
48    sfo_http::http_util::http_post_json2(url, param).await.map_err(into_bucky_err!("request url {} failed", url))
49}
50#[derive(Clone)]
51pub struct HttpClient {
52    client: sfo_http::http_util::HttpClient,
53}
54
55impl Debug for HttpClient {
56    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
57        write!(f, "HttpClient")
58    }
59}
60
61impl HttpClient {
62    pub fn new(max_connections: usize, base_url: Option<&str>) -> Self {
63        Self {
64            client: sfo_http::http_util::HttpClient::new(max_connections, base_url),
65        }
66    }
67
68    pub fn new_with_no_cert_verify(max_connections: usize, base_url: Option<&str>) -> Self {
69        Self {
70            client: sfo_http::http_util::HttpClient::new_with_no_cert_verify(max_connections, base_url),
71        }
72    }
73
74    pub async fn get_json<T: for<'de> Deserialize<'de>>(&self, uri: &str) -> BuckyResult<T> {
75        self.client.get_json(uri).await.map_err(into_bucky_err!())
76    }
77
78    pub async fn get(&self, uri: &str) -> BuckyResult<(Vec<u8>, Option<String>)> {
79        self.client.get(uri).await.map_err(into_bucky_err!())
80    }
81
82    pub async fn post_json<T: for<'de> Deserialize<'de>, P: Serialize>(&self, uri: &str, param: &P) -> BuckyResult<T> {
83        self.client.post_json(uri, param).await.map_err(into_bucky_err!())
84    }
85
86    pub async fn post(&self, uri: &str, param: Vec<u8>, content_type: Option<&str>) -> BuckyResult<(Vec<u8>, Option<String>)> {
87        self.client.post(uri, param, content_type).await.map_err(into_bucky_err!())
88    }
89}
90
91#[derive(Default)]
92pub struct HttpClientBuilder {
93    builder: sfo_http::http_util::HttpClientBuilder
94}
95
96impl HttpClientBuilder {
97    pub fn set_base_url(mut self, base_url: &str) -> Self {
98        self.builder = self.builder.set_base_url(base_url);
99        self
100    }
101    pub fn add_header(
102        mut self,
103        name: impl Into<HeaderName>,
104        value: impl Into<HeaderValue>,
105    ) -> BuckyResult<Self> {
106        self.builder = self.builder.add_header(name, value).map_err(into_bucky_err!())?;
107        Ok(self)
108    }
109
110    pub fn set_http_keep_alive(mut self, keep_alive: bool) -> Self {
111        self.builder = self.builder.set_http_keep_alive(keep_alive);
112        self
113    }
114
115    pub fn set_tcp_no_delay(mut self, no_delay: bool) -> Self {
116        self.builder = self.builder.set_tcp_no_delay(no_delay);
117        self
118    }
119
120    pub fn set_timeout(mut self, timeout: Option<Duration>) -> Self {
121        self.builder = self.builder.set_timeout(timeout);
122        self
123    }
124
125    pub fn set_max_connections_per_host(mut self, max_connections_per_host: usize) -> Self {
126        self.builder = self.builder.set_max_connections_per_host(max_connections_per_host);
127        self
128    }
129
130    pub fn set_verify_tls(mut self, verify_tls: bool) -> Self {
131        self.builder = self.builder.set_verify_tls(verify_tls);
132        self
133    }
134
135    pub fn build(self) -> HttpClient {
136        HttpClient {
137            client: self.builder.build(),
138        }
139    }
140}
141
142#[derive(Serialize, Deserialize)]
143pub struct HttpJsonResult<T>
144{
145    pub err: u16,
146    pub msg: String,
147    pub result: Option<T>
148}
149
150impl <T> HttpJsonResult<T>
151    where T: Serialize
152{
153    pub fn from(ret: BuckyResult<T>) -> Self {
154        match ret {
155            Ok(data) => {
156                HttpJsonResult {
157                    err: 0,
158                    msg: "".to_string(),
159                    result: Some(data)
160                }
161            },
162            Err(err) => {
163                HttpJsonResult {
164                    err: err.code().into(),
165                    msg: format!("{}", err),
166                    result: None
167                }
168            }
169        }
170    }
171
172    pub fn to_response(&self) -> Response {
173        let mut resp = Response::new(StatusCode::Ok);
174        resp.set_content_type("application/json");
175        resp.set_body(serde_json::to_string(self).unwrap());
176        resp
177    }
178}