0

I generated a text file having HTTP Request Response headers with response body. I want to search inside this file looking for response headers containing Access-Control-Allow-Origin: * as a header.

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

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

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

Do I need some complex regex?

With my code I can not 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
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Akash Panchal
  • 205
  • 1
  • 6
  • 20

1 Answers1

1

Your if statement is using the wrong operator.

if  line =~ /Access-Control-Allow-Origin: */
Marc Talbot
  • 2,059
  • 2
  • 21
  • 27
  • The `=~` operator doesn't have a "backwards": `'foo' =~ /o/ # => 1` and `/o/ =~ 'foo' # => 1`. – the Tin Man Feb 24 '12 at 17:34
  • this is not working for me it prints message `No Access-Control-Allow-Origin: * found` always though header is there in file with line `-> "Access-Control-Allow-Origin: *\r\n"`. Please tell me if need to make some complex regex to catch this line or not – Akash Panchal Feb 25 '12 at 06:24
  • The above program cannot print `No Access-Control-Allow-Origin: * found` - there is no such message in it. – Armali Mar 17 '14 at 13:32