class SimpleHttp
Constants
- DEFAULTPORT
- DEFAULT_ACCEPT
- HTTP_VERSION
- RECVSIZE
- RESOLVER
- SEP
Public Class Methods
new(address, port = DEFAULTPORT)
click to toggle source
# File enzi-lib.rb, line 759 def initialize(address, port = DEFAULTPORT) @socket @uri = {} @uri[:address] = address @uri[:port] = port ? port.to_i : DEFAULTPORT self end
Public Instance Methods
address()
click to toggle source
# File enzi-lib.rb, line 767 def address; @uri[:address]; end
create_request_header(method, req)
click to toggle source
# File enzi-lib.rb, line 811 def create_request_header(method, req) req = {} unless req str = "" body = "" str += sprintf("%s %s %s", method, @uri[:path], HTTP_VERSION) + SEP header = {} req.each do |key,value| header[key.capitalize] = value end header["Host"] = @uri[:address] unless header.keys.include?("Host") header["Accept"] = DEFAULT_ACCEPT unless header.keys.include?("Accept") header["Connection"] = "close" if header["Body"] body = header["Body"] header.delete("Body") end if method == "POST" && (not header.keys.include?("content-length".capitalize)) header["Content-Length"] = (body || '').length end header.keys.sort.each do |key| str += sprintf("%s: %s", key, header[key]) + SEP end str + SEP + body end
get(path = "/", req = nil)
click to toggle source
# File enzi-lib.rb, line 770 def get(path = "/", req = nil) request("GET", path, req) end
port()
click to toggle source
# File enzi-lib.rb, line 768 def port; @uri[:port]; end
post(path = "/", req = nil)
click to toggle source
# File enzi-lib.rb, line 774 def post(path = "/", req = nil) request("POST", path, req) end
request(method, path, req)
click to toggle source
private
# File enzi-lib.rb, line 779 def request(method, path, req) @uri[:path] = path if @uri[:path].nil? @uri[:path] = "/" elsif @uri[:path][0] != "/" @uri[:path] = "/" + @uri[:path] end request_header = create_request_header(method.upcase.to_s, req) response_text = send_request(request_header) SimpleHttpResponse.new(response_text) end
resolve(hostname)
click to toggle source
# File enzi-lib.rb, line 806 def resolve(hostname) addr = RESOLVER[hostname.downcase] addr ? addr : hostname end
send_request(request_header)
click to toggle source
# File enzi-lib.rb, line 791 def send_request(request_header) @socket = TCPSocket.new(resolve(@uri[:address]), @uri[:port]) @socket.send(request_header) response_text = nil while response_text.nil? response_text = @socket.recv(RECVSIZE) end while t = @socket.recv(RECVSIZE) response_text += t end @socket.close response_text end