Skip to content

Commit

Permalink
HTTP::Client: execute before_requestcallbacks right before writing …
Browse files Browse the repository at this point in the history
…the request
  • Loading branch information
asterite committed Jan 22, 2018
1 parent fd55e8d commit ff02d2d
Showing 1 changed file with 14 additions and 12 deletions.
26 changes: 14 additions & 12 deletions src/http/client.cr
Expand Up @@ -478,7 +478,6 @@ class HTTP::Client
# response.body # => "..."
# ```
def exec(request : HTTP::Request) : HTTP::Client::Response
execute_callbacks(request)
exec_internal(request)
end

Expand All @@ -496,9 +495,7 @@ class HTTP::Client
end

private def exec_internal_single(request)
decompress = set_defaults request
request.to_io(socket)
socket.flush
decompress = send_request(request)
HTTP::Client::Response.from_io?(socket, ignore_body: request.ignore_body?, decompress: decompress)
end

Expand All @@ -517,7 +514,6 @@ class HTTP::Client
# end
# ```
def exec(request : HTTP::Request, &block)
execute_callbacks(request)
exec_internal(request) do |response|
yield response
end
Expand All @@ -544,9 +540,7 @@ class HTTP::Client
end

private def exec_internal_single(request)
decompress = set_defaults request
request.to_io(socket)
socket.flush
decompress = send_request(request)
HTTP::Client::Response.from_io?(socket, ignore_body: request.ignore_body?, decompress: decompress) do |response|
yield response
end
Expand All @@ -559,6 +553,14 @@ class HTTP::Client
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["User-Agent"] ||= "Crystal"
{% if flag?(:without_zlib) %}
Expand All @@ -573,6 +575,10 @@ class HTTP::Client
{% end %}
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`.
#
Expand Down Expand Up @@ -641,10 +647,6 @@ class HTTP::Client
end
end

private def execute_callbacks(request)
@before_request.try &.each &.call(request)
end

private def socket
socket = @socket
return socket if socket
Expand Down

0 comments on commit ff02d2d

Please sign in to comment.