Use switch for multiple conditions

Problem this snippet solves:

You need to make load balancing or whatever else decision based on multiple context information like HTTP host header, URI, Referer header, cookie value, etc.

How to use this snippet:

This code allow to use a single switch command to manage multiple conditions instead of several nested if or switch conditions.

Normal condition :

switch -glob [HTTP::host] {
    "www.example.net" {
        if { [HTTP::header "Referer"] contains "host.example.net" } {
            # do action 1
        } else {
            # do action 2
        }
    }
    "www.example.com" {
        switch -glob [HTTP::header Referer] {
            "*host.example.com" {
                if { [HTTP::method] eq "GET" } {
                    # do action 3
                }
            }
            default {
                # do action 4
            }
        }
    }
}
`</pre>

Using the process described in this codeshare article :

<pre>`switch -glob "[HTTP::host]|[HTTP::header Referer]|[HTTP::method]" {
    "www.example.net|*host.example.net*|*" {
        # do action 1
    }
    "www.example.net|*" {
        # do action 2
    }
    "www.example.com|*host.example.com*|GET" {
        # do action 3
    }
    "www.example.com|*" {
        # do action 4
    }
}

Code :

when HTTP_REQUEST {
        switch -glob "[HTTP::host]|[HTTP::header 'Referer']|[HTTP::uri]" {
            "*|*REFERERPART*|*" -
"*|*|*URIPART*" -
"*HOSTPART*|*|*" {
# do some action
}
"host.example.com|*www.example.net*|*" {
# do some action
}
default {
# do some action
}
        }
}

Tested this on version:

11.3
Updated Jun 06, 2023
Version 2.0
No CommentsBe the first to comment