Url is associated with “Patterns” in starberry. Url patterns is an enum consists of 4 types
Type name | Actual Name | Note |
---|---|---|
LitUrl(String) | Literal(String) | |
RegUrl(String) | Regex(String) | |
AnyUrl() | AnyUrl | This only accepts one string. A path will not be accepted |
AnyDict() | AnyPath | This accepts a path, a string will also be accepted |
TrailingSlash() | Literal(“”) |
*Note: Type name is the function you actually use in your application to define urlpattern where the Actural name is the actual name defined in the enum. You will not use the Actual name very often
By using reg!
macro, you may associate patterns with App or Url instance to register them
For example,
#[url(reg![&APP, LitUrl("test"), RegUrl("[0-9]+")])]
async fn testnumber() -> HttpResponse {
text_response("Number page")
}
Then you may visit this page through the url of /test/123
(Actually you can visit the same page with any number after /test/)
*Note: Please notice there is no trailing slash. The url with or without trailing slash are different
While also note that each UrlPattern can only match one part of the path. Which means that you must not use LitUrl("aaa/bbb")
, instead you should use LitUrl(aaa), LitUrl("bbb")
There is another way of registering url,
APP.reg_from(&[LitUrl("test"), RegUrl("[0-9]+")])
This provides the same effect as the one above, but the grammar is much complicated. Since starberry 0.4.5, we provide the macro to register the Url
You may also define a static url pattern for easier change:
static TEST_URL: SPattern = Lazy::new(|| {LitUrl("test")});
Then you may use
#[url(reg![&APP, TEST_URL, RegUrl("[0-9]+")])]
To register.
Note if you use the old pattern, you must use the .clone
method and add a Reference sign &
before the TEST_URL. This is the reason why we strongly don’t recommand you to use the old grammar.