#URI how to properly enconde query strings

1 messages · Page 1 of 1 (latest)

sacred summit
#

I am very new to zig, I was trying to make a simple http request to get a json.
Here is a snippet of the code:

const uri = try std.Uri.parse(url);
const response = try client.fetch(.{ .method = .GET, .location = .{ .uri = uri }, .extra_headers = headers, .response_writer = writer });

if I provide a valid url without spaces, the request returns successfully, but if I provide something like ?search=hello world it fails. I was hoping it would encode the url properly before sending.

I could of course do it myself before parsing it, but I was hoping there would be a better way to do it.

Please be kind, these have been my first 6 hours using the language. 😄

dense pivot
#

the result of std.Uri.parse assumes that you've given it a mostly valid url. A hacky way would be to just tell zig that the query is not percent encoded by say,

var uri = try std.Uri.parse(url);
uri.query = .{ .raw = uri.query.?.percent_encoded };

Alternatively, just don't give the parser an invalid url and pre-escape your spaces.

sacred summit
#

Thank you for the reply. Unfortunately

uri.query = .{ .raw = uri.query.?.percent_encoded };

doesn't work "error: cannot assign to constant"

I could just escape the spaces, but this is not just about the spaces, is more about properly encode the url string for instance "Günter" -> "G%C3%BCnter".

The only thing I could find was std.fmt.encodePercent, but it looks like it has been removed.

dense pivot
#

error: cannot assign to constant
thats what the var uri was for

You can always construct the Uri in segments yourself using .raw components, which will be percent encoded for you

sacred summit
#

I tried that too but it causes a panic
panic: access of union field 'percent_encoded' while field 'raw' is active

daring tree
#

you cant uri.percent_encoded = ...
you have to uri = .{ .percent_encoded = ...}
the first is assigning to a union field, which is safety checked that the specified field is the active one.
the seccond is creating a new uri then asigning it to the var.