网络请求
http/https
如果您需要在GenUI中使用网络请求(http/https)需要使用插件gen_makepad_http。
您可以参考这个例子: todo待办事项例子
使用Ract安装插件
1ract add gen_makepad_http
 
安装完成后您的GenUI项目中会出现一个.plugins目录,其中包含一个gen_makepad_http/token.toml文件。
添加所需的依赖
请在项目的Cargo.toml中添加如下依赖:
Cargo.toml
1[package]
2# ...
3
4[dependencies]
5gen_macro = "0.1.0"
6serde = "1.0.217"
7lazy_static = "1.5.0"
8serde_json = "1.0.135"
 
在main.rs中注册
其中这个HttpPublisher就被注册到了全局,设置名称为http1,使用init函数进行初始化
main.rs
1use gen_macro::plugin;
2
3fn init() -> HttpPublisher {
4    let mut http = HttpPublisher::new("/url/path");
5    http.basic.protocol = Protocol::Https; // default is http
6    http
7}
8
9plugin! {
10    http1: HttpPublisher => init()
11}
 
在组件中使用
1impl MyView{
2    #[before_mount]
3    fn before_create(&mut self){
4        let _ = http_get!(http_response1);
5    }
6
7    #[http_response]
8    fn http_response1(&mut self, response: &HttpResponse){
9        if response.status_code == 200 {
10            // ...
11        }
12    }
13}
 
请求
当前支持以下几种请求
- GET: 
http_get! 
- POST: 
http_post! 
- PUT: 
http_put! 
- DELETE: 
http_delete! 
- PATCH: 
http_patch! 
这些宏的使用方式都是一样的:
http_get!($Id: tt) 
http_get!($Id: tt, $Url: expr) 
http_get!($Id: tt, $Url: expr, $Patch: expr) 
$Id: 对应响应的函数名 
$Url: 附加到basic url的地址,例如basic_url是localhost:8888/hello,若这个$Url您设置为"/user/get/1",那么完整的url为: localhost:8888/hello/user/get/1 
$Patch: Into<PatchRequest>,简单来说您可以直接使用某个可序列化的类型或PatchRquest 
HttpPublisher
请求发布者,其中您可以配置基本请求配置(BasicConfig)
BasicConfig
NOTE
默认情况下:
- protocol: 
Protocol::Http 
- headers: 
Content-Type: application/json 
 
1#[derive(Debug, Clone)]
2pub struct BasicConfig {
3    pub protocol: Protocol,
4    pub url: String,
5    pub headers: HashMap<HttpRequestHeader, String>,
6}
 
若您需要添加header,请使用:pub fn push_header(&mut self, header: HttpRequestHeader, value: String) ;
Protocol
1#[derive(Debug, Clone, Copy)]
2pub enum Protocol {
3    Http,
4    Https,
5}
 
1#[derive(Hash, Eq, PartialEq, Debug, Clone)]
2pub enum HttpRequestHeader {
3    ContentType,
4    Authorization,
5    Other(String),
6}
 
PatchRequest
1#[derive(Debug, Clone, Default)]
2pub struct PatchRequest {
3    pub params: Option<HashMap<String, String>>,
4    pub headers: Option<HashMap<HttpRequestHeader, String>>,
5    pub body: Option<HttpRequestBody>,
6}
 
HttpRequestBody
Vec<u8> 实现了数据序列化,意思是您只要使用任何被serde进行序列化的数据都可以作为HttpRequestBody