简体   繁体   中英

Building middleware that grabs the IP

I'm trying to write my firsts rack middleware. And need help. I want middleware that find the requestor's IP and if it is in the allowed list of IP continues the request, otherwise it aborts.

The tricky part is I need this to work on heroku where you can't use request.ip: http://developerhemal.tumblr.com/post/3958107290/client-ip-addresses-on-heroku

So I have the following:

class RestrictIP
  def initialize(app, message = "Hello")
    @app = app
    @message = message
  end

  def call(env)
    dup._call(env)
    @ip = env['HTTP_X_REAL_IP'] ||= env['REMOTE_ADDR']
  end

  def each(&block)
    block.call("<!-- #{@ip} -->\n")
    @response.each(&block)
  end
end

This errors with:

NoMethodError (You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]=):

For my first itteration I just want to make sure I can grab and put the requestor's IP on the html doc.

Any rack middleware experts out there? Thanks

As per this post , it appears you could use the following:

ip = env[‘HTTP_X_REAL_IP’] ||= env[‘REMOTE_ADDR’]

I haven't tested this as I'm not on Heroku.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM