http agent get

This commit is contained in:
Kanezoh 2021-04-30 21:37:41 +09:00
parent 24c05487ec
commit 21d9d5749c
3 changed files with 47 additions and 3 deletions

5
main.cr Normal file
View File

@ -0,0 +1,5 @@
require "./src/mechanize.cr"
agent = Mechanize.new
page = agent.get "http://example.com/"
puts page

28
src/http/agent.cr Normal file
View File

@ -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

View File

@ -1,6 +1,17 @@
# TODO: Write documentation for `Mechanize` require "./http/agent"
module Mechanize
class Mechanize
VERSION = "0.1.0" 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 end