有没有更简单的方法来获取http标头的字符串值?

时间:2018-10-21 20:17:51

标签: rust rust-actix

我现在正在尝试Rust和ActixWeb。而且我想知道这是否是从请求中获取内容类型标头的唯一可能性。
在那里,您还必须检查标头是否可用,否则to_str()会出现恐慌...

let req: actix_web::HttpRequest;

let content_type: &str = req
    .request()
    .headers()
    .get(actix_web::http::header::CONTENT_TYPE)
    .unwrap()
    .to_str()
    .unwrap();

2 个答案:

答案 0 :(得分:1)

是的,这是“唯一的”可能性,但这是因为:

  1. 标题可能不存在,headers().get(key)返回Option
  2. 标头可能包含非ASCII字符,并且HeaderValue::to_str可能会失败。

actix-web可让您分别处理这些错误。

为简化起见,您可以创建一个不区分这两个错误的辅助函数:

fn get_content_type<'a>(req: &'a HttpRequest) -> Option<&'a str> {
    req.headers().get("content-type")?.to_str().ok()
}

完整示例:

use actix_web::{web, App, HttpRequest, HttpServer, Responder};

fn main() {
    HttpServer::new(|| App::new().route("/", web::to(handler)))
        .bind("127.0.0.1:8000")
        .expect("Cannot bind to port 8000")
        .run()
        .expect("Unable to run server");
}

fn handler(req: HttpRequest) -> impl Responder {
    if let Some(content_type) = get_content_type(&req) {
        format!("Got content-type = '{}'", content_type)
    } else {
        "No content-type header.".to_owned()
    }
}

fn get_content_type<'a>(req: &'a HttpRequest) -> Option<&'a str> {
    req.headers().get("content-type")?.to_str().ok()
}

哪个会给您结果:

$ curl localhost:8000
No content-type header.⏎
$ curl localhost:8000 -H 'content-type: application/json'
Got content-type = 'application/json'⏎
$ curl localhost:8000 -H 'content-type: ?'
No content-type header.⏎

顺便说一句,您可能对guards感兴趣:

web::route()
    .guard(guard::Get())
    .guard(guard::Header("content-type", "text/plain"))
    .to(handler)

答案 1 :(得分:0)

我在路线上使用以下内容:

#[get("/auth/login")]
async fn login(request: HttpRequest, session: Session) -> Result<HttpResponse, ApiError> {
    let req_headers = request.headers();

    let basic_auth_header = req_headers.get("Authorization");
    let basic_auth: &str = basic_auth_header.unwrap().to_str().unwrap();

    println!("{}", basic_auth); // At this point I have the value of the header as a string

    // ...
}