Forum Discussion

smp_86112's avatar
smp_86112
Icon for Cirrostratus rankCirrostratus
Jun 21, 2010

switch statement conditions

Is there a way to configure switch to handle different "conditions"? For example, I want to take one action if [HTTP::uri] equals one string, but a different action if it starts_with another? Schematically, something I'm looking to do something like this:


when HTTP_REQUEST {
  switch [HTTP::uri] {
    equals "/" { [HTTP::redirect] http://www.myapp.com/somewhere_else }
    starts_with "/custom" { [HTTP::uri] "/new" }
  }
}

So I'd like a single switch statement look at a string pattern, but take different actions based on the value of different operators.

5 Replies

  • Hi SMP,

    You can use the -glob flag for wildcard handling with the switch statement. Here are some examples:

    when HTTP_REQUEST {
       switch -glob [HTTP::uri] {
          "/" {
              Exact match for /
             HTTP::redirect "https://www.myapp.com/somewhere_else"
          }
          "/custom*" {
              URI starts with /custom
             HTTP::redirect "http://www.myapp.com/custom"
          }
          "*gif" -
          "*jpg" -
          "*css" -
              All these cases use the same action.
              URI ends with a static file type
             pool static_http_pool
          }
          "/app[0-9]*" {
              URI starts with /app where  is a digit
             HTTP::redirect "https://www.myapp.com/app"
          }
          "/app?" {
              URI starts with /app? where ? is any single character
              as /app[0-9]* is before this, ? would be any non-digit character
             HTTP::redirect "https://www.myapp.com/app2"
          }
          default {
              No prior match so take some default action
             HTTP::redirect "http://www.myapp.com/default"
          }
       }
    }
    

    The glob style matching is the same as with string match. So you can check the string and switch man pages for details:

    http://www.tcl.tk/man/tcl8.4/TclCmd/switch.htm

    http://www.tcl.tk/man/tcl8.4/TclCmd/string.htm

    Aaron
  • Thanks hoolio, that does the trick. It would be nice if F5 would add examples like these to their switch wiki page.
  • There was an example which used glob style matching on the switch wiki page. I added another example along the lines of the one above.

     

     

    Aaron
  • Thanks Aaron. SMP, As you see examples in the forum threads that show command usage, feel free to add them to the wiki entries.
  • there is also an entire article on various wildcard matches using switch here: http://devcentral.f5.com/Tutorials/TechTips/tabid/63/articleType/ArticleView/articleId/244/Switch-Gone-Wild-Using-Wildcards-with-the-Tcl-switch-command.aspx