How to search for an exact match string in a text file using Ruby?

I created a text file with HTTP Request Response headers with the response body. I want to search in this file for a search for response headers containing Access-Control-Allow-Origin: *as a title.

The file contains this in the form of a line starting with ->and ending with the "following:

-> "Access-Control-Allow-Origin: *\r\n"

How can I search in this text file and print a custom message over the headers of the request response using the condition if?

Do I need some kind of complex regex?

With my code, I cannot get the correct search:

require 'net/http'
require 'uri'
require 'IPAddr'
require 'timeout'

puts "Origin IP:\n\n"
originip = gets()
puts "Start IP:\n\n"
startip = gets()
puts "End IP:\n\n"
endip = gets()
(IPAddr.new("#{startip}")..IPAddr.new("#{endip}")).each do |address|
  begin
   uri = URI("http://#{address.to_s}")
   http = Net::HTTP.new(uri.host, uri.port)
   http.set_debug_output($stdout)
   request = Net::HTTP::Get.new(uri.request_uri)
   request.initialize_http_header({"Origin" => "#{originip}"})
   response = http.request request
   $stdout.reopen('Access-Control-Allow-Origin.txt','a')
   f = File.Open('Access-Control-Allow-Origin.txt')
   line = f.read
   if line = /Access-Control-Allow-Origin: */ then
     puts "\n\nAccess-Control-Allow-Origin: * Header Found:\n\n"
   else
     puts "\n\nAccess-Control-Allow-Origin: * Header Not Found:\n\n"
   end
 rescue Timeout::Error => exc
   puts "ERROR: #{exc.message}"
 rescue Errno::ETIMEDOUT => exc
   puts "ERROR: #{exc.message}"
 rescue Exception => exc
   puts "ERROR: #{exc.message}"
 end
end
0
source share
1 answer

The if statement uses the wrong statement.

if  line =~ /Access-Control-Allow-Origin: */
+1

All Articles