Skip to content

介绍

用于快速发送HTTP请求和解析HTTP响应的库

rust
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

#[derive(Serialize, Deserialize, Debug)]
struct ResponseBody<T> {
    success: bool,
    msg: String,
    data: Option<T>,
}

#[derive(Serialize, Deserialize, Debug)]
struct Pagination<T> {
    page: usize,
    size: usize,
    rows: Vec<T>,
}

#[derive(Serialize, Deserialize, Debug)]
struct Article {
    id: String,
    title: String,
    contents: String,
}

#[derive(Serialize, Deserialize, Debug)]
struct LoginResponse {
    token: String,
}

#[derive(Serialize, Deserialize, Debug)]
struct PatchExampleResponse {
    id: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///////////////////////////////////////
    // 1.send request direct, like this: //
    ///////////////////////////////////////
    let resp: ResponseBody<Pagination<Article>> = reqwest::get("http://localhost:3000/articles")
        .await?
        .json()
        .await?;
    println!("first article title: {}", resp.data.unwrap().rows[0].title);

    //////////////////////////////////////////////////////////////
    // 2.send request after build http client and request body ///
    //////////////////////////////////////////////////////////////
    let http_client = reqwest::Client::new();
    let mut form_data = HashMap::new();
    form_data.insert("email", "admin@example.com");
    form_data.insert("password", "e10adc3949ba59abbe56e057f20f883e"); // md5 origin text: 123456

    let resp: ResponseBody<LoginResponse> = http_client
        .post("http://localhost:3000/login")
        .json(&form_data)
        .send()
        .await? // send request async
        .json()
        .await?; // parse response async
    println!("login response: {:?}", resp.data.unwrap());

    ////////////////////////////////////////////////////////////////
    // 3.send put/patch/delete method request with query and body //
    ////////////////////////////////////////////////////////////////
    let mut query_data = HashMap::new();
    query_data.insert("page", "2");
    query_data.insert("size", "10");

    let mut form_data = HashMap::new();
    form_data.insert("title", "updated-article-title-text");
    let http_client = reqwest::Client::new();
    let resp: ResponseBody<PatchExampleResponse> = http_client
        .patch("http://localhost:3000/article/mock-article-id-string")
        .query(&query_data)
        .json(&form_data)
        .send()
        .await? // send request async
        .json()
        .await?; // parse response async
    println!("patch response: {:?}", resp.data.unwrap());

    Ok(())
}
toml
[dependencies]
reqwest = { version = "0.12", features = ["json"] }
tokio = { version = "1", features = ["full"] }
js
import express from "express";
import cors from "cors";
import Mock from "mockjs";
const { mock } = Mock;

/////////////////////////////////////////////////
//                 init app                    //
/////////////////////////////////////////////////
const app = express();
const config = Object.freeze({
  port: 3000,
  enableCors: true,
  prefix: "/api",
  success(res, data = null) {
    res.json({
      success: true,
      msg: "success",
      data,
    });
  },
  error(res, data = null) {
    res.json({
      success: false,
      msg: "error",
      data,
    });
  },
});

// parse request body
app.use(express.json({ extended: true }));

// enable cors requests
if (config.enableCors) {
  app.use(cors());
}

/////////////////////////////////////////////////
//                  routes                     //
/////////////////////////////////////////////////
const { success, error } = config;
app.get("/", (_, res) => success(res));
app.get("/articles", (_, res) => {
  const articles = mock({
    page: 1,
    size: 10,
    "rows|10": [
      {
        id: "@id",
        title: "@ctitle",
        contents: "@cparagraph",
      },
    ],
  });

  success(res, articles);
});

// for post example
app.post("/login", (_, res) => {
  success(res, {
    "token": "mock-token-string",
  });
});

// for patch/put example
app.patch("/article/:id", (req, res) => {
  success(res, {
    id: req.params.id
  });
});

// for delete example
app.delete("/article/:id", (req, res) => {
  success(res, {
    id: req.params.id
  });
});

/////////////////////////////////////////////////
//                  listen                     //
/////////////////////////////////////////////////
app.listen(config.port, () => {
  const url = `http://localhost:${config.port}`;
  console.log(`server started on: ${url}`);
});
json
{
  "name": "mock-server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "dev": "nodemon server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "express": "^4.20.0",
    "nodemon": "^3.1.4"
  },
  "dependencies": {
    "cors": "^2.8.5",
    "mockjs": "^1.1.0"
  }
}

Released under the MIT License.