Skip to content

Commit 3ad6b10

Browse files
committed
Add crow::url_decode() function for decoding from percent-encoding.
1 parent 3c82cda commit 3ad6b10

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

docs/guides/routes.md

+13
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,19 @@ CROW_ROUTE(app, "/add/<int>/<int>")
2020
```
2121
you can see the first `<int>` is defined as `a` and the second as `b`. If you were to run this and call `http://example.com/add/1/2`, the result would be a page with `3`. Exciting!
2222
23+
Another example is to ask for the first part in a string, and the remainder in a path.
24+
Note that strings are in URL-encoding (aka Percent-encoding, eg `"image%20file.png"`).
25+
To decode into UTF-8, use `crow::decode_url(...)` to in-place decode the string.
26+
```cpp
27+
CROW_ROUTE(app, "/combine/<string>/<path>")
28+
([](std::string first, std::string remainder)
29+
{
30+
// first can remain percent-encoded: perhaps we know for certain that it will always be simple text
31+
crow::decode_url(remainder);
32+
return first + " --> " + remainder;
33+
});
34+
```
35+
2336
## Methods
2437
You can change the HTTP methods the route uses from just the default `GET` by using `method()`, your route macro should look like `CROW_ROUTE(app, "/add/<int>/<int>").methods(crow::HTTPMethod::GET, crow::HTTPMethod::PATCH)` or `CROW_ROUTE(app, "/add/<int>/<int>").methods("GET"_method, "PATCH"_method)`.
2538

include/crow/http_request.h

+16
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,22 @@ namespace crow // NOTE: Already documented in "crow/app.h"
3131
return empty;
3232
}
3333

34+
/// URLs given to routes are in URL-encoding (aka Percent-encoding)
35+
/// eg "image file.png" --> "image%20file.png"
36+
/// This operates on the string in-place and decodes a percent-encoded string to UTF-8
37+
/// The resulting string will always be shorter than the original, so this function
38+
/// will set a new null terminator at the end of the string.
39+
inline int url_decode( char* url )
40+
{
41+
return qs_decode(url);
42+
}
43+
44+
/// This will decode the url in-place, resizing the string to the new shorter size.
45+
inline void url_decode( std::string& url )
46+
{
47+
url.resize( url_decode(&url[0]) );
48+
}
49+
3450
/// An HTTP request.
3551
struct request
3652
{

tests/unittest.cpp

+7
Original file line numberDiff line numberDiff line change
@@ -4116,3 +4116,10 @@ TEST_CASE("option_header_passed_in_full")
41164116
CHECK(res.find(ServerName) != std::string::npos);
41174117
app.stop();
41184118
}
4119+
4120+
TEST_CASE("url_decoding")
4121+
{
4122+
std::string url = "image%20file.png";
4123+
crow::url_decode(url);
4124+
CHECK(url == "image file.png");
4125+
}

0 commit comments

Comments
 (0)