icyleaf / halite

💎HTTP Requests Client with a chainable REST API, built-in sessions and middlewares.
MIT License
170 stars 13 forks source link

New Interceptor to features #32

Closed icyleaf closed 6 years ago

icyleaf commented 6 years ago

Now you can intercept each request and return any response without starting the real http request. of cause you also can performing the HTTP request, after then cook and return.

For example:

Creating a simple mock feature:

class Mock < Halite::Feature
  def intercept(chain)
    response = Halite::Response.new(chain.request.uri, 400, "[]")
    chain.return(response)
  end

  Halite::Features.register "mock", self
end

r = Halite.use("mock").get("http://httpbin.org/anything")
r.status_code    # => 400
r.body           # => []

chain is a Halite::Interceptor::Chain class which has two result:

So, you can intercept and turn to the following registered features.

class AlwaysNotFound < Halite::Feature
  def intercept(chain)
    response = chain.perform
    response = Halite::Response.new(chain.request.uri, 404, response.body, response.headers)
    chain.next(response)
  end

  Halite::Features.register "404", self
end

class PoweredBy < Halite::Feature
  def intercept(chain)
    if response = chain.response
      response.headers["X-Powered-By"] = "Halite"
      chain.return(response)
    else
      chain
    end
  end

  Halite::Features.register "powered_by", self
end

r = Halite.use("404").use("powered_by").get("http://httpbin.org/user-agent")
r.status_code               # => 404
r.headers["X-Powered-By"]   # => Halite
r.body                      # => {"user-agent":"Halite/0.6.0"}
icyleaf commented 6 years ago

Related to #29