Search code examples
rustactix-web

Generate a very plain URL with Actix web which has no further params


How do I supply nothing when generating a URL in Actix web for Rust?

req.request().url_for(website::RESOURCE_LOGIN, nothing_to_go_here);

The url_for method is forcing me to supply an iterator as the second arg.

The URL is just /something. Seems odd to force me to consume memory for nothing.

Here's the sig:

    pub fn url_for<U, I>(&self, name: &str, elements: U) -> Result<url::Url, UrlGenerationError>
    where
        U: IntoIterator<Item = I>,
        I: AsRef<str>,

If I use &[] it needs type annotations, which I'm too noob to know. So I'll supply &[""] and carry on. It seems like it should take an Option.

error[E0282]: type annotations needed
   --> src/lib.rs:100:39
    |
    |         let login_url = req.request().url_for(website::RESOURCE_LOGIN, &[]);
    |                                       ^^^^^^^                          --- type must be known at this point
    |                                       |
    |                                       cannot infer type of the type parameter `U` declared on the method `url_for`
help: consider specifying the generic arguments
    |
    |         let login_url = req.request().url_for::<&[_; 0], &T>(website::RESOURCE_LOGIN, &[]);
    |                                              +++++++++++++++

Okay so the compiler say to use this

::<&[_; 0], &T>

And that leads to this:

102 |             .url_for::<&[_; 0], &T>(website::RESOURCE_LOGIN, &[]);
    |                                  ^ not found in this scope
    |
help: you might be missing a type parameter
    |
92  | async fn check_auth<T>(
    |                    +++

I have no idea what's going on now.


Solution

  • I see a url_for_static method you can use instead. It does exactly what you're after:

    This method is similar to HttpRequest::url_for() but it can be used for urls that do not contain variable parts.

    For those curious, its implementation looks like this:

    pub fn url_for_static(&self, name: &str) -> Result<url::Url, UrlGenerationError> {
        const NO_PARAMS: [&str; 0] = [];
        self.url_for(name, NO_PARAMS)
    }