Parsing a GUID out of a Header



Hat tip to user fookanen for this post which was the basis of this post.

So the question came up recently: how to I extract a GUID out of the header in an HTTP request?

Let’s walk through this in multiple steps.

Step 1 : Pick the Event

The app guys said the GUID we are looking for is specified on the HTTP request, so we need our trigger to fire on the HTTP_REQUEST event.

That’s easy enough. Just pick HTTP_REQUEST in the Events box when building your trigger.

Step 2 : Find The Header

The Header we care about is the X-Session-ID header. We know this because the app guys said so. :slight_smile:

Here is how we access a specific header in an HTTP Request:

// get the full value for X-Session-ID
var raw = HTTP.headers["X-Session-ID"];

We end up with the variable raw holding something like this:


We care about just this part:


Step 3 : Pull out the GUID

Next step. Pull the GUID from that raw value up above.

Note that the key/value pairs in the X-Session-ID header are separated with an asterisk. That’s handy. Really handy.

Here is how we pull out the GUID:

var result = /\*guid=([^*]+)\*/.exec(raw);

Let’s deconstruct that regular expression:

/        start regex definition
  \\*        literal *   (i.e. the asterisk character)
  guid=     text to match
  (         start slurping stuff into memory
    [^\*]+      find a bunch of characters that are NOT an asterisk
  )         stop slurping
  \\*        literal asterisk
/        end regex definition

Step 4 : Defensive Programming

Best practice says that we should try and handle when things don’t go as expected.

Here’s how.

var raw = HTTP.headers["X-Session-ID"];
// did we get the header we need?
if( raw ) {
    // we got the header, let's parse it
    var result = /\*guid=([^*]+)\*/.exec(raw);
    // test if the parse worked
    if( result ) {
        // the parse worked, extract the first value
        var guid = result[1];
        // We have the GUID 
        // here is where we do something with it.
        // maybe put on the for use on the response side
        // maybe put into an Application
        // maybe . . . 

Hope this was helpful.