简体   繁体   中英

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

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?

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:

在此输入图像描述

Hope it helps! :-]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM