Rocket
信息
响应
参考:Responder in rocket::response - Rust
// `T` 必须实现 `Responder`。
#[get("/")]
fn index() -> T { /* ... */ }
状态码
src/main.rs
#[macro_use]
extern crate rocket;
use rocket::http::Status;
use rocket::response::status::Custom;
#[get("/")]
fn index() -> Custom<&'static str> {
Custom(Status::Ok, "Hello Rocket!")
}
#[launch]
fn rocket() -> _ {
rocket::build().mount("/", routes![index])
}
自定义 Header
src/main.rs
#[macro_use]
extern crate rocket;
mod structs;
mod routes;
use rocket::http::{ContentType, Header};
use rocket::response::Responder;
#[derive(Responder)]
#[response(status = 202, content_type = "json")]
struct IndexResponder {
inner: String,
headers: ContentType,
more: Header<'static>,
}
#[get("/")]
fn index() -> IndexResponder {
IndexResponder {
inner: "abc".parse().unwrap(),
headers: ContentType::Text,
more: Header::new(
"X-Authlib-Injector-API-Location",
// heighline
"https://skin.mc.yue.zone/api/yggdrasil",
),
}
}
#[launch]
fn rocket() -> _ {
rocket::build().mount("/", routes![index])
}
JSON
参考:rocket::serde::json - Rust | Serde
该模块仅在启用 json
特性时可用。
编辑 Cargo.toml
文件启用该特性:
Cargo.toml
[dependencies.rocket]
version = "=0.5.0-rc.3"
features = ["json"]
src/main.rs
#[macro_use]
extern crate rocket;
use rocket::serde::{Serialize, json::Json};
#[derive(Serialize)]
#[serde(crate = "rocket::serde", rename_all = "camelCase")]
struct IndexMetaLinks {
homepage: String,
register: String,
}
#[derive(Serialize)]
#[serde(crate = "rocket::serde", rename_all = "camelCase")]
struct IndexMeta {
server_name: String,
implementation_name: String,
implementation_version: String,
links: IndexMetaLinks,
}
#[derive(Serialize)]
#[serde(crate = "rocket::serde", rename_all = "camelCase")]
struct Index {
meta: IndexMeta,
skin_domains: Vec<String>,
signature_publickey: String,
}
#[get("/")]
fn index() -> Json<Index> {
Json(Index {
meta: IndexMeta {
server_name: String::from("YueZoneYggdrasil"),
implementation_name: String::from("YueZone Minecraft Skin Site"),
implementation_version: String::from("0.0.0"),
links: IndexMetaLinks {
homepage: String::from("http://localhost:8000/"),
register: String::from("http://localhost:8000/register"),
},
},
skin_domains: vec![
String::from("localhost"),
String::from("yue.zone"),
],
signature_publickey: String::from("-----BEGIN PUBLIC KEY-----"),
})
}
#[launch]
fn rocket() -> _ {
rocket::build().mount("/", routes![index])
}
HTTP GET /
{
"meta": {
"serverName": "YueZoneYggdrasil",
"implementationName": "YueZone Minecraft Skin Site",
"implementationVersion": "0.0.0",
"links": {
"homepage": "http://localhost:8000/",
"register": "http://localhost:8000/register"
}
},
"skinDomains": [
"localhost",
"yue.zone"
],
"signaturePublicKey": "-----BEGIN PUBLIC KEY-----"
}