Skip to content

Instantly share code, notes, and snippets.

@rousan
Last active April 8, 2018 06:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rousan/c65fdac9b80664fbc7f7edeba2dba4d4 to your computer and use it in GitHub Desktop.
Save rousan/c65fdac9b80664fbc7f7edeba2dba4d4 to your computer and use it in GitHub Desktop.
How ServeMux works in Golang http route multiplexing

How Does ServeMux Work in Golang?

Types of Route Pattern

There are two types of pattern registered:

  • Fixed named pattern (without trailing slash e.g. /about, /home)

  • Rooted path or subtree (with trailing slash e.g. /, /about/)

Steps for Route Matching


Let the requested route is RP:

1. If RP ends with trailing slash

  1. List down all the Rooted path or subtrees pattern which satisfies the condition: RP.startsWith(pattern)
  
  2. If One or more Patterns satisfies
  
    1. Pick the longest pattern
    
    2. Call the handler associated with picked pattern
    
  3. If No patterns found
  
    1. Response with Not Found routing
    
2. If RP does not end with trailing slash

  1. Find exact match for RP among the registered Fixed named patterns
  
    1. If Match found
  
       1. Call the handler associated with matched pattern
   
    2. If Match not found
  
       1. Check whether a pattern is registered with RP + \
   
         1. If Pattern is registered
   
            1. Redirect to that pattern i.e. RP + \
      
         2. If Pattern is not registered
         
            1. List down all the Rooted path or subtrees pattern which satisfies the condition: RP.startsWith(pattern)
            
            2. If One or more Patterns satisfies
            
              1. Pick the longest pattern
              
              2. Call the handler associated with picked pattern
              
            3. No patterns found
            
              1. Response with Not Found routing
              
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment