How do I set default error pages for the underlying Webrick server?
I have a very simple webrick server for embedded device admin pages. We just added basic authentication to the device and it works great, but you get a generic "unauthorized" message:
<!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?
source to share
Looking at the source code, it looks like it 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 of type @reason_phrase
and ex.code
. In your case, you can use ex.code
(ex:) 401
to specify other content if you like.
Here's a complete example that you can run in a console irb
that displays a custom error page (note that this assumes that there is a directory named in your filesystem Public
):
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 doesn't exist) you should see a custom error page, like this:
Hope this helps!: -]
source to share