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

1

5

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?

Thumbprint answered 15/7, 2015 at 23:38 Comment(0)
A
8

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! :-]

Adonic answered 10/10, 2015 at 21:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.