How to dump an HTTP request from within Sinatra?

后端 未结 2 1985
-上瘾入骨i
-上瘾入骨i 2020-12-23 12:08

Is there a way to dump all incoming requests to a Sinatra application in the exact way the application receives the data? Maybe some sort of Rack middleware?

2条回答
  •  悲&欢浪女
    2020-12-23 12:48

    Maybe this is not what you're asking, but I arrived here looking for a way to see all the HTTP request headers in Sinatra (without actually having to enumerate them, to debug a proxied request). I found this quite useful:

    get "/my_route" do
      puts "#{ request.env }"
    end
    

    Or, to return that blob in the response in a legible json format:

    require 'json'
    get "/my_route" do
      content_type :text
      return JSON.pretty_generate(request.env)
    end
    

    And voila, all the request details:

    {
      "SERVER_SOFTWARE": "thin 1.6.2 codename Doc Brown",
      "SERVER_NAME": "10.0.1.3",
      "rack.input": "#",
      "rack.version": [
        1,
        0
      ],
      "rack.errors": "#",
      "rack.multithread": false,
      "rack.multiprocess": false,
      "rack.run_once": false,
      "REQUEST_METHOD": "GET",
      "REQUEST_PATH": "/my_route",
      "PATH_INFO": "/my_route",
      "REQUEST_URI": "/my_route",
      "HTTP_VERSION": "HTTP/1.0",
      "HTTP_X_FORWARDED_FOR": "10.0.1.3, 127.0.0.1, 127.0.0.1, 127.0.0.1",
      "HTTP_HOST": "10.0.1.3:9393",
      "HTTP_CONNECTION": "close",
      "HTTP_X_REAL_IP": "10.0.1.3",
      "HTTP_X_FE_SCHEME": "http",
      "HTTP_X_FE_HOST": "10.0.10.145",
      "HTTP_X_FE_ROUTE": "/my_route",
      "HTTP_ACCEPT": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
      "HTTP_USER_AGENT": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36",
      "HTTP_ACCEPT_LANGUAGE": "en-US,en;q=0.8",
      "HTTP_X_VARNISH": "917254702",
      "HTTP_ACCEPT_ENCODING": "gzip",
      "GATEWAY_INTERFACE": "CGI/1.2",
      "SERVER_PORT": "9393",
      "QUERY_STRING": "",
      "SERVER_PROTOCOL": "HTTP/1.1",
      "rack.url_scheme": "http",
      "SCRIPT_NAME": "",
      "REMOTE_ADDR": "10.0.10.145",
      "async.callback": "#",
      "async.close": "#",
      "rack.logger": "#",
      "rack.request.query_string": "",
      "rack.request.query_hash": {
      },
      "sinatra.route": "GET (?-mix:^\\/my_route$)"
    }
    

提交回复
热议问题