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开发者_如何学C
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.
精彩评论