C
C
caiser2012-10-03 13:57:40
ruby
caiser, 2012-10-03 13:57:40

Rack work without middleware?

require "net/http"
require "stringio"

class Worker
def call(env)
  request = Rack::Request.new(env)
  case request.request_method
  when "POST"
    [200,{"Content-Type"=>"text/plain"},StringIO.new("")]
  when "GET", "PUT", "DELETE", "OPTION", "HEAD"
    [404,{"Content-Type"=>"text/plain"}, StringIO.new("Not Found")]
  end
 create_response(request.body.read)
end

def create_response(body)
  uri = URI("server2")
  res = Net::HTTP::Post.new(uri.request_uri)
  res.content_type = 'text/plain'
  Net::HTTP.start(uri.hostname, uri.port) {|http| http.request(res, body) }
  return [200,{"Content-Type"=>"text/plain"},StringIO.new("")] # если не возвращать эту строку rack'y - будет ошибка
end
end

run Worker.new

I run the following code through rackup.
How it works ( scheme 1 ): I simulate (assume from server2) a POST request by sending it via curl with the -d option, specifying any value as the body. The rack sends the received request (server1) for processing to the create_response method, where it passes the value of the request body as an argument. That, in turn, sends its POST (server1 to server2) and receives 200 OK in response, then rack sends 200 OK to the client where curl was launched.
How I want it to work ( Scheme 2 ):
The code above is S2. For S1, the code will be about the same, with some exceptions, suppose S1 is always the initiator of the entire scheme.
When a request is received (step 1), if it is POST, immediately send (step 2) 200 OK, in other cases 404 Not Found and end there. After that, a POST is sent from S2 to S1 (step 3) and we receive (step 4) a response.
Tried to implement it via
lambda { |env| [200,{"Content-Type"=>"text/plain"},StringIO.new("")] }

The same situation.
In both cases, Thin was used as the web server.
Question: How to do it? I will be glad for any hints.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question