Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HTTP::Client: execute before_requestcallbacks right before writing the request #5626

Merged
merged 1 commit into from
Jan 22, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 14 additions & 12 deletions src/http/client.cr
Original file line number Diff line number Diff line change
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