如何在actix-web中将查询字符串传递给HttpRequest.url_for()?

时间:2019-04-26 13:16:25

标签: rust rust-actix actix-web

Documentation关于url_for。

代码:

fn index(req: HttpRequest) -> HttpResponse {
    let url = req.url_for("foo", &["1", "2", "3"]); // <- generate url for "foo" resource
    HTTPOk.into()
}

fn main() {
    let app = Application::new()
        .resource("/test/{one}/{two}/{three}", |r| {
             r.name("foo");  // <- set resource name, then it could be used in `url_for`
             r.method(Method::GET).f(|_| httpcodes::HTTPOk);
        })
        .finish();
}

如何向生成的URL中添加诸如?name=Alex之类的查询字符串?有没有使用HttpRequest.url_for()的内置方法(不仅仅是像url += query_str那样追加)

1 个答案:

答案 0 :(得分:0)

url_for为您提供了Result<Url, Error>,您可以对其进行解包和使用.set_query

req.url_for("foo", &["1", "2", "3"]).unwrap().set_query(Some("q=asdf"));