-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathclient.cr
862 lines (792 loc) · 25.6 KB
/
client.cr
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
# An HTTP Client.
#
# ### One-shot usage
#
# Without a block, an `HTTP::Client::Response` is returned and the response's body
# is available as a `String` by invoking `HTTP::Client::Response#body`.
#
# ```
# require "http/client"
#
# response = HTTP::Client.get "http://www.example.com"
# response.status_code # => 200
# response.body.lines.first # => "<!doctype html>"
# ```
#
# ### Parameters
#
# Parameters can be added to any request with the `HTTP::Params#encode` method, which
# converts a `Hash` or `NamedTuple` to a URL encoded HTTP query.
#
# ```
# require "http/client"
#
# params = HTTP::Params.encode({"author" => "John Doe", "offset" => "20"}) # => author=John+Doe&offset=20
# response = HTTP::Client.get "http://www.example.com?" + params
# response.status_code # => 200
# ```
#
# ### Streaming
#
# With a block, an `HTTP::Client::Response` body is returned and the response's body
# is available as an `IO` by invoking `HTTP::Client::Response#body_io`.
#
# ```
# require "http/client"
#
# HTTP::Client.get("http://www.example.com") do |response|
# response.status_code # => 200
# response.body_io.gets # => "<!doctype html>"
# end
# ```
#
# ### Reusing a connection
#
# Similar to the above cases, but creating an instance of an `HTTP::Client`.
#
# ```
# require "http/client"
#
# client = HTTP::Client.new "www.example.com"
# response = client.get "/"
# response.status_code # => 200
# response.body.lines.first # => "<!doctype html>"
# client.close
# ```
#
# ### Compression
#
# If `compress` isn't set to `false`, and no `Accept-Encoding` header is explicitly specified,
# an HTTP::Client will add an `"Accept-Encoding": "gzip, deflate"` header, and automatically decompress
# the response body/body_io.
#
# ### Encoding
#
# If a response has a `Content-Type` header with a charset, that charset is set as the encoding
# of the returned IO (or used for creating a String for the body). Invalid bytes in the given encoding
# are silently ignored when reading text content.
class HTTP::Client
# The set of possible valid body types.
alias BodyType = String | Bytes | IO | Nil
# Returns the target host.
#
# ```
# require "http/client"
#
# client = HTTP::Client.new "www.example.com"
# client.host # => "www.example.com"
# ```
getter host : String
# Returns the target port.
#
# ```
# require "http/client"
#
# client = HTTP::Client.new "www.example.com"
# client.port # => 80
# ```
getter port : Int32
# If this client uses TLS, returns its `OpenSSL::SSL::Context::Client`, raises otherwise.
#
# Changes made after the initial request will have no effect.
#
# ```
# require "http/client"
#
# client = HTTP::Client.new "www.example.com", tls: true
# client.tls # => #<OpenSSL::SSL::Context::Client ...>
# ```
{% if flag?(:without_openssl) %}
getter! tls : Nil
{% else %}
getter! tls : OpenSSL::SSL::Context::Client
{% end %}
# Whether automatic compression/decompression is enabled.
property? compress : Bool
{% if flag?(:without_openssl) %}
@socket : TCPSocket | Nil
{% else %}
@socket : TCPSocket | OpenSSL::SSL::Socket | Nil
{% end %}
@dns_timeout : Float64?
@connect_timeout : Float64?
@read_timeout : Float64?
# Creates a new HTTP client with the given *host*, *port* and *tls*
# configurations. If no port is given, the default one will
# be used depending on the *tls* arguments: 80 for if *tls* is `false`,
# 443 if *tls* is truthy. If *tls* is `true` a new `OpenSSL::SSL::Context::Client` will
# be used, else the given one. In any case the active context can be accessed through `tls`.
{% if flag?(:without_openssl) %}
def initialize(@host : String, port = nil, tls : Bool = false)
check_host_only(@host)
@tls = nil
if tls
raise "HTTP::Client TLS is disabled because `-D without_openssl` was passed at compile time"
end
@port = (port || (@tls ? 443 : 80)).to_i
@compress = true
end
{% else %}
def initialize(@host : String, port = nil, tls : Bool | OpenSSL::SSL::Context::Client = false)
check_host_only(@host)
@tls = case tls
when true
OpenSSL::SSL::Context::Client.new
when OpenSSL::SSL::Context::Client
tls
when false
nil
end
@port = (port || (@tls ? 443 : 80)).to_i
@compress = true
end
{% end %}
private def check_host_only(string : String)
# When parsing a URI with just a host
# we end up with a URI with just a path
uri = URI.parse(string)
if uri.scheme || uri.host || uri.port || uri.query || uri.user || uri.password || uri.path.includes?('/')
raise_invalid_host(string)
end
rescue URI::Error
raise_invalid_host(string)
end
private def raise_invalid_host(string : String)
raise ArgumentError.new("The string passed to create an HTTP::Client must be just a host, not #{string.inspect}")
end
# Creates a new HTTP client from a URI. Parses the *host*, *port*,
# and *tls* configuration from the URI provided. Port defaults to
# 80 if not specified unless using the https protocol, which defaults
# to port 443 and sets tls to `true`.
#
# ```
# require "http/client"
# require "uri"
#
# uri = URI.parse("https://secure.example.com")
# client = HTTP::Client.new(uri)
#
# client.tls? # => #<OpenSSL::SSL::Context::Client>
# client.get("/")
# ```
# This constructor will *ignore* any path or query segments in the URI
# as those will need to be passed to the client when a request is made.
#
# If *tls* is given it will be used, if not a new TLS context will be created.
# If *tls* is given and *uri* is a HTTP URI, `ArgumentError` is raised.
# In any case the active context can be accessed through `tls`.
#
# This constructor will raise an exception if any scheme but HTTP or HTTPS
# is used.
def self.new(uri : URI, tls = nil)
tls = tls_flag(uri, tls)
host = validate_host(uri)
new(host, uri.port, tls)
end
# Creates a new HTTP client from a URI, yields it to the block and closes the
# client afterwards. Parses the *host*, *port*, and *tls* configuration from
# the URI provided. Port defaults to 80 if not specified unless using the
# https protocol, which defaults to port 443 and sets tls to `true`.
#
# ```
# require "http/client"
# require "uri"
#
# uri = URI.parse("https://secure.example.com")
# HTTP::Client.new(uri) do |client|
# client.tls? # => #<OpenSSL::SSL::Context::Client>
# client.get("/")
# end
# ```
# This constructor will *ignore* any path or query segments in the URI
# as those will need to be passed to the client when a request is made.
#
# If *tls* is given it will be used, if not a new TLS context will be created.
# If *tls* is given and *uri* is a HTTP URI, `ArgumentError` is raised.
# In any case the active context can be accessed through `tls`.
#
# This constructor will raise an exception if any scheme but HTTP or HTTPS
# is used.
def self.new(uri : URI, tls = nil)
tls = tls_flag(uri, tls)
host = validate_host(uri)
client = new(host, uri.port, tls)
begin
yield client
ensure
client.close
end
end
# Creates a new HTTP client, yields it to the block, and closes
# the client afterwards.
#
# ```
# require "http/client"
#
# HTTP::Client.new("www.example.com") do |client|
# client.get "/"
# end
# ```
def self.new(host : String, port = nil, tls = false)
client = new(host, port, tls)
begin
yield client
ensure
client.close
end
end
# Configures this client to perform basic authentication in every
# request.
def basic_auth(username, password)
header = "Basic #{Base64.strict_encode("#{username}:#{password}")}"
before_request do |request|
request.headers["Authorization"] = header
end
end
# Sets the number of seconds to wait when reading before raising an `IO::Timeout`.
#
# ```
# require "http/client"
#
# client = HTTP::Client.new("example.org")
# client.read_timeout = 1.5
# begin
# response = client.get("/")
# rescue IO::Timeout
# puts "Timeout!"
# end
# ```
def read_timeout=(read_timeout : Number)
@read_timeout = read_timeout.to_f
end
# Sets the read timeout with a `Time::Span`, to wait when reading before raising an `IO::Timeout`.
#
# ```
# require "http/client"
#
# client = HTTP::Client.new("example.org")
# client.read_timeout = 5.minutes
# begin
# response = client.get("/")
# rescue IO::Timeout
# puts "Timeout!"
# end
# ```
def read_timeout=(read_timeout : Time::Span)
self.read_timeout = read_timeout.total_seconds
end
# Sets the number of seconds to wait when connecting, before raising an `IO::Timeout`.
#
# ```
# require "http/client"
#
# client = HTTP::Client.new("example.org")
# client.connect_timeout = 1.5
# begin
# response = client.get("/")
# rescue IO::Timeout
# puts "Timeout!"
# end
# ```
def connect_timeout=(connect_timeout : Number)
@connect_timeout = connect_timeout.to_f
end
# Sets the open timeout with a `Time::Span` to wait when connecting, before raising an `IO::Timeout`.
#
# ```
# require "http/client"
#
# client = HTTP::Client.new("example.org")
# client.connect_timeout = 5.minutes
# begin
# response = client.get("/")
# rescue IO::Timeout
# puts "Timeout!"
# end
# ```
def connect_timeout=(connect_timeout : Time::Span)
self.connect_timeout = connect_timeout.total_seconds
end
# **This method has no effect right now**
#
# Sets the number of seconds to wait when resolving a name, before raising an `IO::Timeout`.
#
# ```
# require "http/client"
#
# client = HTTP::Client.new("example.org")
# client.dns_timeout = 1.5
# begin
# response = client.get("/")
# rescue IO::Timeout
# puts "Timeout!"
# end
# ```
def dns_timeout=(dns_timeout : Number)
@dns_timeout = dns_timeout.to_f
end
# **This method has no effect right now**
#
# Sets the number of seconds to wait when resolving a name with a `Time::Span`, before raising an `IO::Timeout`.
#
# ```
# require "http/client"
#
# client = HTTP::Client.new("example.org")
# client.dns_timeout = 1.5.seconds
# begin
# response = client.get("/")
# rescue IO::Timeout
# puts "Timeout!"
# end
# ```
def dns_timeout=(dns_timeout : Time::Span)
self.dns_timeout = dns_timeout.total_seconds
end
# Adds a callback to execute before each request. This is usually
# used to set an authorization header. Any number of callbacks
# can be added.
#
#
# ```
# require "http/client"
#
# client = HTTP::Client.new("www.example.com")
# client.before_request do |request|
# request.headers["Authorization"] = "XYZ123"
# end
# client.get "/"
# ```
def before_request(&callback : HTTP::Request ->)
before_request = @before_request ||= [] of (HTTP::Request ->)
before_request << callback
end
{% for method in %w(get post put head delete patch options) %}
# Executes a {{method.id.upcase}} request.
# The response will have its body as a `String`, accessed via `HTTP::Client::Response#body`.
#
# ```
# require "http/client"
#
# client = HTTP::Client.new("www.example.com")
# response = client.{{method.id}}("/", headers: HTTP::Headers{"User-Agent" => "AwesomeApp"}, body: "Hello!")
# response.body #=> "..."
# ```
def {{method.id}}(path, headers : HTTP::Headers? = nil, body : BodyType = nil) : HTTP::Client::Response
exec {{method.upcase}}, path, headers, body
end
# Executes a {{method.id.upcase}} request and yields the response to the block.
# The response will have its body as an `IO` accessed via `HTTP::Client::Response#body_io`.
#
# ```
# require "http/client"
#
# client = HTTP::Client.new("www.example.com")
# client.{{method.id}}("/", headers: HTTP::Headers{"User-Agent" => "AwesomeApp"}, body: "Hello!") do |response|
# response.body_io.gets #=> "..."
# end
# ```
def {{method.id}}(path, headers : HTTP::Headers? = nil, body : BodyType = nil)
exec {{method.upcase}}, path, headers, body do |response|
yield response
end
end
# Executes a {{method.id.upcase}} request.
# The response will have its body as a `String`, accessed via `HTTP::Client::Response#body`.
#
# ```
# require "http/client"
#
# response = HTTP::Client.{{method.id}}("/", headers: HTTP::Headers{"User-Agent" => "AwesomeApp"}, body: "Hello!")
# response.body #=> "..."
# ```
def self.{{method.id}}(url : String | URI, headers : HTTP::Headers? = nil, body : BodyType = nil, tls = nil) : HTTP::Client::Response
exec {{method.upcase}}, url, headers, body, tls
end
# Executes a {{method.id.upcase}} request and yields the response to the block.
# The response will have its body as an `IO` accessed via `HTTP::Client::Response#body_io`.
#
# ```
# require "http/client"
#
# HTTP::Client.{{method.id}}("/", headers: HTTP::Headers{"User-Agent" => "AwesomeApp"}, body: "Hello!") do |response|
# response.body_io.gets #=> "..."
# end
# ```
def self.{{method.id}}(url : String | URI, headers : HTTP::Headers? = nil, body : BodyType = nil, tls = nil)
exec {{method.upcase}}, url, headers, body, tls do |response|
yield response
end
end
# Executes a {{method.id.upcase}} request with form data and returns a `Response`. The "Content-Type" header is set
# to "application/x-www-form-urlencoded".
#
# ```
# require "http/client"
#
# client = HTTP::Client.new "www.example.com"
# response = client.{{method.id}} "/", form: "foo=bar"
# ```
def {{method.id}}(path, headers : HTTP::Headers? = nil, *, form : String | IO) : HTTP::Client::Response
request = new_request({{method.upcase}}, path, headers, form)
request.headers["Content-Type"] = "application/x-www-form-urlencoded"
exec request
end
# Executes a {{method.id.upcase}} request with form data and yields the response to the block.
# The response will have its body as an `IO` accessed via `HTTP::Client::Response#body_io`.
# The "Content-Type" header is set to "application/x-www-form-urlencoded".
#
# ```
# require "http/client"
#
# client = HTTP::Client.new "www.example.com"
# client.{{method.id}}("/", form: "foo=bar") do |response|
# response.body_io.gets
# end
# ```
def {{method.id}}(path, headers : HTTP::Headers? = nil, *, form : String | IO)
request = new_request({{method.upcase}}, path, headers, form)
request.headers["Content-Type"] = "application/x-www-form-urlencoded"
exec(request) do |response|
yield response
end
end
# Executes a {{method.id.upcase}} request with form data and returns a `Response`. The "Content-Type" header is set
# to "application/x-www-form-urlencoded".
#
# ```
# require "http/client"
#
# client = HTTP::Client.new "www.example.com"
# response = client.{{method.id}} "/", form: {"foo" => "bar"}
# ```
def {{method.id}}(path, headers : HTTP::Headers? = nil, *, form : Hash(String, String) | NamedTuple) : HTTP::Client::Response
body = HTTP::Params.encode(form)
{{method.id}} path, form: body, headers: headers
end
# Executes a {{method.id.upcase}} request with form data and yields the response to the block.
# The response will have its body as an `IO` accessed via `HTTP::Client::Response#body_io`.
# The "Content-type" header is set to "application/x-www-form-urlencoded".
#
# ```
# require "http/client"
#
# client = HTTP::Client.new "www.example.com"
# client.{{method.id}}("/", form: {"foo" => "bar"}) do |response|
# response.body_io.gets
# end
# ```
def {{method.id}}(path, headers : HTTP::Headers? = nil, *, form : Hash(String, String) | NamedTuple)
body = HTTP::Params.encode(form)
{{method.id}}(path, form: body, headers: headers) do |response|
yield response
end
end
# Executes a {{method.id.upcase}} request with form data and returns a `Response`. The "Content-Type" header is set
# to "application/x-www-form-urlencoded".
#
# ```
# require "http/client"
#
# response = HTTP::Client.{{method.id}} "http://www.example.com", form: "foo=bar"
# ```
def self.{{method.id}}(url, headers : HTTP::Headers? = nil, tls = nil, *, form : String | IO | Hash) : HTTP::Client::Response
exec(url, tls) do |client, path|
client.{{method.id}}(path, form: form, headers: headers)
end
end
# Executes a {{method.id.upcase}} request with form data and yields the response to the block.
# The response will have its body as an `IO` accessed via `HTTP::Client::Response#body_io`.
# The "Content-Type" header is set to "application/x-www-form-urlencoded".
#
# ```
# require "http/client"
#
# HTTP::Client.{{method.id}}("http://www.example.com", form: "foo=bar") do |response|
# response.body_io.gets
# end
# ```
def self.{{method.id}}(url, headers : HTTP::Headers? = nil, tls = nil, *, form : String | IO | Hash)
exec(url, tls) do |client, path|
client.{{method.id}}(path, form: form, headers: headers) do |response|
yield response
end
end
end
{% end %}
# Executes a request.
# The response will have its body as a `String`, accessed via `HTTP::Client::Response#body`.
#
# ```
# require "http/client"
#
# client = HTTP::Client.new "www.example.com"
# response = client.exec HTTP::Request.new("GET", "/")
# response.body # => "..."
# ```
def exec(request : HTTP::Request) : HTTP::Client::Response
exec_internal(request)
end
private def exec_internal(request)
response = exec_internal_single(request)
return handle_response(response) if response
# Server probably closed the connection, so retry one
close
request.body.try &.rewind
response = exec_internal_single(request)
return handle_response(response) if response
raise "Unexpected end of http response"
end
private def exec_internal_single(request)
decompress = send_request(request)
HTTP::Client::Response.from_io?(socket, ignore_body: request.ignore_body?, decompress: decompress)
end
private def handle_response(response)
close unless response.keep_alive?
response
end
# Executes a request request and yields an `HTTP::Client::Response` to the block.
# The response will have its body as an `IO` accessed via `HTTP::Client::Response#body_io`.
#
# ```
# require "http/client"
#
# client = HTTP::Client.new "www.example.com"
# client.exec(HTTP::Request.new("GET", "/")) do |response|
# response.body_io.gets # => "..."
# end
# ```
def exec(request : HTTP::Request, &block)
exec_internal(request) do |response|
yield response
end
end
private def exec_internal(request, &block : Response -> T) : T forall T
exec_internal_single(request) do |response|
if response
return handle_response(response) { yield response }
end
# Server probably closed the connection, so retry once
close
request.body.try &.rewind
exec_internal_single(request) do |response|
if response
return handle_response(response) do
yield response
end
end
end
end
raise "Unexpected end of http response"
end
private def exec_internal_single(request)
decompress = send_request(request)
HTTP::Client::Response.from_io?(socket, ignore_body: request.ignore_body?, decompress: decompress) do |response|
yield response
end
end
private def handle_response(response)
value = yield
response.body_io?.try &.close
close unless response.keep_alive?
value
end
private def send_request(request)
decompress = set_defaults request
run_before_request_callbacks(request)
request.to_io(socket)
socket.flush
decompress
end
private def set_defaults(request)
request.headers["Host"] ||= host_header
request.headers["User-Agent"] ||= "Crystal"
{% if flag?(:without_zlib) %}
false
{% else %}
if compress? && !request.headers.has_key?("Accept-Encoding")
request.headers["Accept-Encoding"] = "gzip, deflate"
true
else
false
end
{% end %}
end
# For one-shot headers we don't want keep-alive (might delay closing the response)
private def self.default_one_shot_headers(headers)
headers ||= HTTP::Headers.new
headers["Connection"] ||= "close"
headers
end
private def run_before_request_callbacks(request)
@before_request.try &.each &.call(request)
end
# Executes a request.
# The response will have its body as a `String`, accessed via `HTTP::Client::Response#body`.
#
# ```
# require "http/client"
#
# client = HTTP::Client.new "www.example.com"
# response = client.exec "GET", "/"
# response.body # => "..."
# ```
def exec(method : String, path, headers : HTTP::Headers? = nil, body : BodyType = nil) : HTTP::Client::Response
exec new_request method, path, headers, body
end
# Executes a request.
# The response will have its body as an `IO` accessed via `HTTP::Client::Response#body_io`.
#
# ```
# require "http/client"
#
# client = HTTP::Client.new "www.example.com"
# client.exec("GET", "/") do |response|
# response.body_io.gets # => "..."
# end
# ```
def exec(method : String, path, headers : HTTP::Headers? = nil, body : BodyType = nil)
exec(new_request(method, path, headers, body)) do |response|
yield response
end
end
# Executes a request.
# The response will have its body as an `IO` accessed via `HTTP::Client::Response#body_io`.
#
# ```
# require "http/client"
#
# response = HTTP::Client.exec "GET", "http://www.example.com"
# response.body # => "..."
# ```
def self.exec(method, url : String | URI, headers : HTTP::Headers? = nil, body : BodyType = nil, tls = nil) : HTTP::Client::Response
headers = default_one_shot_headers(headers)
exec(url, tls) do |client, path|
client.exec method, path, headers, body
end
end
# Executes a request.
# The response will have its body as an `IO` accessed via `HTTP::Client::Response#body_io`.
#
# ```
# require "http/client"
#
# HTTP::Client.exec("GET", "http://www.example.com") do |response|
# response.body_io.gets # => "..."
# end
# ```
def self.exec(method, url : String | URI, headers : HTTP::Headers? = nil, body : BodyType = nil, tls = nil)
headers = default_one_shot_headers(headers)
exec(url, tls) do |client, path|
client.exec(method, path, headers, body) do |response|
yield response
end
end
end
# Closes this client. If used again, a new connection will be opened.
def close
@socket.try &.close
@socket = nil
end
private def new_request(method, path, headers, body : BodyType)
HTTP::Request.new(method, path, headers, body)
end
private def socket
socket = @socket
return socket if socket
hostname = @host.starts_with?('[') && @host.ends_with?(']') ? @host[1..-2] : @host
socket = TCPSocket.new hostname, @port, @dns_timeout, @connect_timeout
socket.read_timeout = @read_timeout if @read_timeout
socket.sync = false
{% if !flag?(:without_openssl) %}
if tls = @tls
tcp_socket = socket
begin
socket = OpenSSL::SSL::Socket::Client.new(tcp_socket, context: tls, sync_close: true, hostname: @host)
rescue exc
# don't leak the TCP socket when the SSL connection failed
tcp_socket.close
raise exc
end
end
{% end %}
@socket = socket
end
private def host_header
if (@tls && @port != 443) || (!@tls && @port != 80)
"#{@host}:#{@port}"
else
@host
end
end
private def self.exec(string : String, tls = nil)
uri = URI.parse(string)
unless uri.scheme && uri.host
# Assume http if no scheme and host are specified
uri = URI.parse("http://#{string}")
end
exec(uri, tls) do |client, path|
yield client, path
end
end
{% if flag?(:without_openssl) %}
protected def self.tls_flag(uri, context : Nil)
scheme = uri.scheme
case scheme
when nil
raise ArgumentError.new("Missing scheme: #{uri}")
when "http"
false
when "https"
true
else
raise ArgumentError.new "Unsupported scheme: #{scheme}"
end
end
{% else %}
protected def self.tls_flag(uri, context : OpenSSL::SSL::Context::Client?)
scheme = uri.scheme
case {scheme, context}
when {nil, _}
raise ArgumentError.new("Missing scheme: #{uri}")
when {"http", nil}
false
when {"http", OpenSSL::SSL::Context::Client}
raise ArgumentError.new("TLS context given for HTTP URI")
when {"https", nil}
true
when {"https", OpenSSL::SSL::Context::Client}
context
else
raise ArgumentError.new "Unsupported scheme: #{scheme}"
end
end
{% end %}
protected def self.validate_host(uri)
host = uri.host
return host if host && !host.empty?
raise ArgumentError.new %(Request URI must have host (URI is: #{uri}))
end
private def self.exec(uri : URI, tls = nil)
tls = tls_flag(uri, tls)
host = validate_host(uri)
port = uri.port
path = uri.full_path
user = uri.user
password = uri.password
HTTP::Client.new(host, port, tls) do |client|
if user && password
client.basic_auth(user, password)
end
yield client, path
end
end
end
{% if !flag?(:without_openssl) %}
require "openssl"
{% end %}
require "socket"
require "uri"
require "base64"
require "./client/response"
require "./common"