2

Documentation about url_for.

Code:

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();
}

How can I add to generated URL a query string like ?name=Alex? Is there a nice built in way to do it using HttpRequest.url_for() (not just append like url += query_str)

Alex
  • 51
  • 4

1 Answers1

2

url_for gives you a Result<Url, UrlGenerationError>, which you can unwrap and add query parameters using .set_query.

let mut myurl = req.url_for("foo", &["1", "2", "3"]).unwrap();
myurl.set_query(Some("q=asdf"));
simanacci
  • 2,197
  • 3
  • 26
  • 35
arve0
  • 3,424
  • 26
  • 33