Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the default error pages for a basic Webrick server?

Tags:

ruby

webrick

I have a very basic webrick server running for the admin pages of an embedded device. We just added basic authentication to the device and it works great, but you get the generic "unauthorized" message back like this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<HTML>
  <HEAD><TITLE>Unauthorized</TITLE></HEAD>
  <BODY>
    <H1>Unauthorized</H1>
    WEBrick::HTTPStatus::Unauthorized
    <HR>
    <ADDRESS>
     WEBrick/1.3.1 (Ruby/2.2.0/2014-12-25) at
     192.168.1.1:1234
    </ADDRESS>
  </BODY>
</HTML>

Does anyone know how to override this to return a static HTML file?

like image 1000
DaKaZ Avatar asked Mar 16 '23 09:03

DaKaZ


1 Answers

Looking at the source code, it looks like httpresponse.rb has a "hook" called create_error_page:

  if respond_to?(:create_error_page)
    create_error_page()
    return
  end

So, if you add your own Ruby method called create_error_page in WEBrick::HTTPResponse, you can set your own markup:

module WEBrick
  class HTTPResponse
    def create_error_page
      @body = ''
      @body << <<-_end_of_html_
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<HTML>
  <HEAD><TITLE>#{HTMLUtils::escape(@reason_phrase)}</TITLE></HEAD>
  <BODY>
    <H1>#{HTMLUtils::escape(@reason_phrase)}</H1>
    <HR>
    <P>Custom error page!</P>
  </BODY>
</HTML>
      _end_of_html_
    end
  end
end

Note that you have access to variables like @reason_phrase and ex.code. In your case, you can use ex.code (eg: 401) to set different content if you wish.

Here is a full example that you can run in an irb console that displays a custom error page (note that it assumes you have a directory called Public in your file system):

require 'webrick'

module WEBrick
  class HTTPResponse
    def create_error_page
      @body = ''
      @body << <<-_end_of_html_
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<HTML>
  <HEAD><TITLE>#{HTMLUtils::escape(@reason_phrase)}</TITLE></HEAD>
  <BODY>
    <H1>#{HTMLUtils::escape(@reason_phrase)}</H1>
    <HR>
    <P>Custom error page!</P>
  </BODY>
</HTML>
      _end_of_html_
    end
  end
end

root = File.expand_path '~/Public'
server = WEBrick::HTTPServer.new :Port => 8000, :DocumentRoot => root
trap 'INT' do server.shutdown end
server.start

When you go to http://localhost:8000/bogus (a page that does not exist), you should see the custom error page, like so:

enter image description here

Hope it helps! :-]

like image 56
Enrique Delgado Avatar answered May 06 '23 18:05

Enrique Delgado