Created
December 4, 2014 09:58
-
-
Save BugRoger/f02c609cbb177dfc7199 to your computer and use it in GitHub Desktop.
HTTPClient
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class HTTPClient | |
VERB_MAP = { | |
get: Net::HTTP::Get, | |
post: Net::HTTP::Post, | |
put: Net::HTTP::Put, | |
delete: Net::HTTP::Delete | |
} | |
def initialize(endpoint, options = {}) | |
uri = URI.parse(endpoint) | |
@username = options[:username] | |
@password = options[:password] | |
@http = Net::HTTP.new(uri.host, uri.port) | |
end | |
def get(path, params) | |
request_json :get, path, params | |
end | |
def post(path, params) | |
request_json :post, path, params | |
end | |
def put(path, params) | |
request_json :put, path, params | |
end | |
def delete(path, params) | |
request_json :delete, path, params | |
end | |
private | |
def basic_auth? | |
@username && @password | |
end | |
def request_json(method, path, params) | |
response = request(method, path, params) | |
result = case response | |
when Net::HTTPSuccess | |
begin | |
JSON.parse response.body | |
rescue JSON::ParserError | |
{ error: "Response is not valid JSON" } | |
end | |
when Net::HTTPUnauthorized | |
{ error: response.message } | |
when Net::HTTPServerError | |
{ error: response.message } | |
else | |
{ error: response.message } | |
end | |
[response.code.to_i, result] | |
end | |
def request(method, path, params = {}) | |
case method | |
when :get | |
full_path = encode_path_params(path, params) | |
request = VERB_MAP[method].new(full_path) | |
else | |
request = VERB_MAP[method].new(path) | |
request.set_form_data(params) | |
end | |
request.basic_auth @username, @password if basic_auth? | |
response = @http.request(request) | |
end | |
def encode_path_params(path, params) | |
encoded = URI.encode_www_form(params) | |
[path, encoded].join("?") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment