Crystal: Using uri.path instead of String brakes HTTP::Client#get

Created on 15 Sep 2018  路  3Comments  路  Source: crystal-lang/crystal

Submitting bugs

This code works as expected:

require "http/client"

uri = URI.parse "https://example.com/help"
client = HTTP::Client.new uri
client.get("/help") { |_| puts "hello" }

But with this change it fails:

 uri = URI.parse "https://example.com/help"
 client = HTTP::Client.new uri
+client.get(uri.path) { |_| puts "hello" }
-client.get("/help") { |_| puts "hello" }

I expect uri.path should work, because it holds the same string as "/help":

uri.path == "/help" # => true

carc.in


Crystal 0.26.1 [391785249] (2018-08-27)
LLVM: 4.0.0
Default target: x86_64-unknown-linux-gnu

Most helpful comment

You probably want uri.path || "/" here, since https://example.com will have a nil path, whereas you probably want that to be the same as https://example.com/

All 3 comments

The error happens because uri.path can return nil. (The union type in the error is (String | Nil)).
A way to handle this is:

require "http/client"

uri = URI.parse "https://example.com/help"
client = HTTP::Client.new uri
if path = uri.path
  client.get(path) { |_| puts "hello" }
end

The if path = uri.path check ensures that path is not nil.

You probably want uri.path || "/" here, since https://example.com will have a nil path, whereas you probably want that to be the same as https://example.com/

Note: #6323 would change the return type of URI#path to String and this would have worked as expected from the beginning.

Was this page helpful?
0 / 5 - 0 ratings