#rest-client #proc-macro #rest #client #macro #serde

restcrab

过程宏,用于从特质定义自动生成REST客户端

4个版本

0.2.0 2022年7月14日
0.1.2 2022年1月25日
0.1.1 2021年9月16日
0.1.0 2021年9月13日

#378 in HTTP客户端

MIT 协议

15KB
186 代码行

Restcrab

crates.io docs.rs

Restcrab提供了一个过程宏 restcrab 和一个特质 Restcrab,可以从特质定义生成REST客户端。

用法

use std::collections::HashMap;

use serde::{Serialize, Deserialize};
use restcrab::{restcrab, Restcrab, crabs::reqwest};

#[derive(Serialize, Deserialize)]
struct Request {
  id: i32
}

#[derive(Serialize, Deserialize)]
struct Response {
  message: String
}

#[restcrab(crab = "reqwest::Reqwest")]
trait Service {
  #[restcrab(method = "GET", uri = "/empty")]
  fn uri_from_attribute();

  #[restcrab(method = "GET", uri = "/empty/{name}")]
  fn uri_from_attribute_with_parameter(#[parameter] name: &str);

  #[restcrab(method = "GET")]
  fn uri_from_method_name();

  #[restcrab(method = "GET", uri = "/static_header", header("Content-Type", "application/json"))]
  fn static_header();

  #[restcrab(method = "GET", uri = "/static_headers", header("Content-Type", "application/json"), header("User-Agen", "Restcrab"))]
  fn static_headers();

  #[restcrab(method = "GET", uri = "/static_query", query("some", "query"), query("another", "one"))]
  fn static_query();

  #[restcrab(method = "POST", uri = "/static_body", body = "0")]
  fn static_body() -> String;

  #[restcrab(method = "POST", uri = "/dynamic_headers")]
  fn dynamic_headers(#[headers] headers: HashMap<String, String>) -> String;

  #[restcrab(method = "POST", uri = "/dynamic_queries")]
  fn dynamic_queries(#[queries] queries: HashMap<String, String>) -> String;

  #[restcrab(method = "POST", uri = "/dynamic_headers", header("Content-Type", "application/json"))]
  fn both_headers(#[headers] headers: HashMap<String, String>) -> String;

  #[restcrab(method = "POST", uri = "/dynamic_body")]
  fn dynamic_body(#[body] body: Request) -> Response;
}

fn main() {
  let client = ServiceClient::from_options(reqwest::Options {
    base_url: "https://service.url".parse().unwrap()
  }).unwrap(); 

  let mut headers = HashMap::new();
  headers.insert("User-Agen".to_string(), "Restcrab".to_string());

  let uri_from_attribute:   ()        = client.uri_from_attribute().unwrap();
  let uri_from_method_name: ()        = client.uri_from_method_name().unwrap();
  let static_header:        ()        = client.static_header().unwrap();
  let static_headers:       ()        = client.static_headers().unwrap();
  let static_body:          String    = client.static_body().unwrap();
  let dynamic_headers:      String    = client.dynamic_headers(headers.clone()).unwrap();
  let both_headers:         String    = client.both_headers(headers).unwrap();
  let dynamic_body:         Response  = client.dynamic_body(Request { id: 0 }).unwrap();
}

模块化后端(crabs)

因为我喜欢使用不友好的术语,所以restcrab的后端被称为crab。

实现了 Restcrab 特质的类型可以用作crab。

该Crate提供了一个使用 Reqwest HTTP客户端的crab。

如果您想实现自己的crab,请查看 提供的实现 作为起点

依赖项

~4–17MB
~240K SLoC