如何在Rails 6中将Ngrok隧道动态添加到config.hosts?

问题描述 投票:1回答:1

我正在尝试将config.hosts中的ngrok隧道主机名列入白名单,但是每次启动Ngrok时,它都会更改。有没有办法获取我的Ngrok隧道的公共URL,这样我就不必使用hosts.clear

ruby-on-rails ruby ngrok
1个回答
2
投票

Ngrok具有内置的JSON API,可以在localhost:4040/api/tunnels上找到。

# lib/ngrok_client.rb
module NgrokClient
  def self.tunnels
    response = Net::HTTP.get(URI('http://localhost:4040/api/tunnels'))
    begin
      JSON.parse(response).dig("tunnels")
    rescue JSON::ParserError => e
      Rails.logger.error %q{
        Failed to parse reponse from Ngroks internal API. Are you sure its running?
      }
    end
  end
  def self.public_urls
    tunnels.select do |h|
      # TODO - don't hardcode the host name
      h.dig("config", "addr") == "http://localhost:3000"
    end.map { |h| URI(h["public_url"]).hostname }.uniq
  end
end
# config/environments/development.rb
Rails.application.configure do
  # ...
  require 'ngrok_client'
  config.hosts += NgrokClient.public_urls
end

[还有ngrok-tunnel宝石可用于从中间件层启动ngrok,以减少黑客的攻击。

© www.soinside.com 2019 - 2024. All rights reserved.