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
Crystal 0.26.1 [391785249] (2018-08-27)
LLVM: 4.0.0
Default target: x86_64-unknown-linux-gnu
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.
Most helpful comment
You probably want
uri.path || "/"here, sincehttps://example.comwill have a nil path, whereas you probably want that to be the same ashttps://example.com/