简体   繁体   English

构建抓取IP的中间件

[英]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. 我希望中间件找到请求者的IP,如果它在允许的IP列表中继续请求,否则它将中止。

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 棘手的部分是我需要这个在heroku上工作,你不能使用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. 对于我的第一次尝试,我只想确保我可以抓住并将请求者的IP放在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. 我没有测试过这个,因为我不在Heroku上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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