我正在尝试将config.hosts
中的ngrok隧道主机名列入白名单,但是每次启动Ngrok时,它都会更改。有没有办法获取我的Ngrok隧道的公共URL,这样我就不必使用hosts.clear
?
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,以减少黑客的攻击。