Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Chu Yeow http://blog.codefront.net/

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

WEBrick servlet with HTTP authentication

// HTTP authentication for a directory listing


require 'webrick'
include WEBrick

dir = Dir::pwd
port = 1234

authenticate = Proc.new do |req, res|
  HTTPAuth.basic_auth(req, res, '') do |user, password|
    user == 'foo' && password == 'bar'
  end
end

s = HTTPServer.new(:Port => port, :ServerType => Daemon)
s.mount('/', HTTPServlet::FileHandler, dir,
  :FancyIndexing => true,
  :HandlerCallback => authenticate # Hook up the authentication proc.
)

trap('INT') { s.shutdown }
s.start

WEBrick servlet skeleton

// Skeleton code for a WEBrick servlet.

require 'webrick'
include WEBrick
class UberServlet < HTTPServlet::AbstractServlet

  def do_GET(req, res)
    id = req.query['id'] # Get GET/POST params like that.
    res['content-type'] = 'text/html'
    res.status = 200
    res.body = some_text
  end
  alias :do_POST :do_GET

end

# "Mount" the servlet.
server = HTTPServer.new(:Port => 1234)
server.mount('/some/path', UberServlet)

# Handle signals.
%w(INT TERM).each do |signal|
  trap(signal) { server.shutdown }
end

server.start
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS