From 21d9d5749caf9a02f0a4bd26930e18da58610bed Mon Sep 17 00:00:00 2001 From: Kanezoh Date: Fri, 30 Apr 2021 21:37:41 +0900 Subject: [PATCH] http agent get --- main.cr | 5 +++++ src/http/agent.cr | 28 ++++++++++++++++++++++++++++ src/mechanize.cr | 17 ++++++++++++++--- 3 files changed, 47 insertions(+), 3 deletions(-) create mode 100644 main.cr create mode 100644 src/http/agent.cr diff --git a/main.cr b/main.cr new file mode 100644 index 0000000..aabcfb2 --- /dev/null +++ b/main.cr @@ -0,0 +1,5 @@ +require "./src/mechanize.cr" + +agent = Mechanize.new +page = agent.get "http://example.com/" +puts page diff --git a/src/http/agent.cr b/src/http/agent.cr new file mode 100644 index 0000000..87df571 --- /dev/null +++ b/src/http/agent.cr @@ -0,0 +1,28 @@ +require "uri" +require "http/client" + +module MechanizeCr + module HTTP + class Agent + def initialize() + end + + def fetch(uri, method = :get, headers = HTTP::Headers.new) + response = http_request uri, method, headers + puts response.not_nil!.body + end + + def http_request(uri, method, headers) + uri = URI.parse(uri) + request = ::HTTP::Client.new(uri.host.not_nil!) + case uri.scheme.not_nil!.downcase + when "http", "https" then + case method + when :get + request.get(uri.path, headers: headers) + end + end + end + end + end +end diff --git a/src/mechanize.cr b/src/mechanize.cr index 8f4ebe1..5550706 100644 --- a/src/mechanize.cr +++ b/src/mechanize.cr @@ -1,6 +1,17 @@ -# TODO: Write documentation for `Mechanize` -module Mechanize +require "./http/agent" + +class Mechanize VERSION = "0.1.0" - # TODO: Put your code here + def initialize() + @agent = MechanizeCr::HTTP::Agent.new + end + + def get(uri : String | URI, headers = headers = HTTP::Headers.new) + method = :get + page = @agent.fetch uri, method, headers + #add_to_history(page) + #yield page if block_given? + page + end end