Search code examples
rubyserverlistener

How to get Headers from request?


I am trying to create a webhook. I am brand new to Ruby, but am setting up a very simple practice server. Each time a new issue/ticket is created for one of my github repos, a POST request is made to a URL that I have setup to grab the payload. I am loosely following this tutorial.

I am able to access all the elements that are being posted in the actual payload/body using this code:

require 'sinatra'
require 'json'

post '/payload' do
    request.body.rewind
    payload_body = request.body.read
    puts payload_body

How can I grab the contents of the header? I have been scrolling through documentation, but have had no luck. I tried accessing the header through response and request.headers and received this error: NoMethodError - undefined method `headers' for #<Sinatra::Request:0x0000000006de49e0> Please let me know if I am missing something here. Thank you.

Here is an example of the headers from my POST request:

Request URL: http://505db39aa8ef.ngrok.io:
Request method: POST
Accept: */*
content-type: application/json
User-Agent: GitHub-Hookshot/cf3e7e0
X-GitHub-Delivery: 8d7fe080-ecc2-11ea-9b34-d35efaaf3885
X-GitHub-Event: issues
X-GitHub-Hook-ID: 245792914
X-GitHub-Hook-Installation-Target-ID: 279687508
X-GitHub-Hook-Installation-Target-Type: repository
X-Hub-Signature: sha1=ed12f9e7a31b08f9109557d6a9dd899ca85de9b5


Solution

  • request.get_header('HTTP_X_GITHUB_HOOK_INSTALLATION_TARGET_TYPE')
    # or
    request.env['HTTP_X_GITHUB_HOOK_INSTALLATION_TARGET_TYPE']
    

    It is worth mentioning that,sinatra will process custom header:

    • add prefix HTTP_
    • capitalize every letter
    • gsub - to _

    You can use request.env to access all headers.
    For detail information about what variable will be added HTTP_ you can refer there