Get请求
curl "http://127.0.0.1:8000/get/cat?task_id=123&demo=1"
Post请求
curl 'http://localhost:8000/set/monkey' \
-H "Content-Type:application/json" \
-H 'Authorization:bearer' \
-X POST \
-d '{"name":"xiaoming", "age":12}'
curl 'http://localhost:8000/set/monkey' \
-H "Content-Type:application/json" \
-H 'Authorization:bearer' \
-X POST \
-d '@/Users/xxx/test.json'
cat test.json
{
"name":"xiaoming", "age":12}
代码示例
// cat Cargo.toml
[package]
name = "rust_demo7"
version = "0.1.0"
edition = "2021"
[dependencies]
hyper = {
version = "0.14", features = ["full"] }
tokio = {
version = "1", features = ["full"] }
futures = "0.3"
url = "2.2"
serde = {
version = "1.0", features = ["derive"] }
serde_json = "1.0"
// cat src/main.rs
use hyper::{
Server, Body, Method, Request, Response, StatusCode};
use hyper::service::{
make_service_fn, service_fn};
use std::convert::Infallible;
use std::net::SocketAddr;
use serde::{
Deserialize, Serialize};
#[derive(Debug, Deserialize)]
struct MyData {
name: String,
age: u32,
}
async fn handle_request(req: Request<Body>) -> Result<Response<Body>, hyper::Error> {
match (req.method(), req.uri().path()) {
(&Method::GET, "/watch/dog") => {
print!("enter Get logic\n");
let params: Vec<(String, String)> = req
.uri()
.query()
.map(|query| {
url::form_urlencoded::parse(query.as_bytes())
.into_owned()
.collect()
})
.unwrap_or_else(Vec::new);
// 打印参数
for (key, value) in params {
println!("{} = {}", key, value);
}
Ok(Response::new(Body::from("Hello, World!"