Search code examples
rubyhttphttp-headerswebrick

How to add code to set headers to a simple ruby webrick command line?


When I need a test web server that can serve a few files from some directory, I really like the simplicity of

ruby -run -e httpd . -p 8888

then browse to localhost:8888.

However, sometimes I'd like to add a tiny little bit to that, for example, set a specific mime type for a specific extension (I can edit /usr/lib/ruby/2.3.0/webrick/httputils.rb, but I'd rather not mess with system files), or add an Expires: header.

It seems like adding a header isn't that complicated, for example, looking at https://www.thecodingforums.com/threads/setting-expires-http-response-header.822995/.

However, I have zero knowledge about ruby, so I have no clue about how to add that to my command line. I guess it's just "create a file that has a subclass, pull it in, and tell ruby to use the subclass", but well .. that answer is 3 steps beyond me.

So, I'd be grateful for an answer that says "Put this into a file, then add that to your command line", with copy/pasteable examples of this and that.


Solution

  • Ok. Put this into a file server.rb for example:

    require 'webrick'                                                                                                          
    
    class Server < WEBrick::HTTPServer                                                                                         
      def service(req, res)                                                                                                    
        super                                                                                                                  
        one_hour = 60 * 60                                                                                                     
        t = Time.now.gmtime + one_hour
        res['Expires'] = t.strftime("%a, %d %b %Y %H:%M:%S GMT")
      end                                                                                                                      
    end                                                                                                                        
    
    root = File.expand_path('.')                                                                                               
    server = Server.new(Port: 8000, DocumentRoot: root)                                                                        
    
    trap('INT') { server.shutdown } # Ctrl-C to stop                                                                                            
    
    server.start 
    

    Then run this in console:

    ruby server.rb
    

    It will serve files list from current directory.