github.com/google/martian/v3@v3.3.3/martianurl/host.go (about)

     1  // Copyright 2016 Google Inc. All rights reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package martianurl
    16  
    17  // MatchHost matches two URL hosts with support for wildcards.
    18  func MatchHost(host, match string) bool {
    19  	// Short circuit if host is empty.
    20  	if host == "" {
    21  		return false
    22  	}
    23  
    24  	// Exact match, no need to loop.
    25  	if host == match {
    26  		return true
    27  	}
    28  
    29  	// Walk backward over the host.
    30  	hi := len(host) - 1
    31  	for mi := len(match) - 1; mi >= 0; mi-- {
    32  		// Found wildcard, skip to next period.
    33  		if match[mi] == '*' {
    34  			for hi > 0 && host[hi] != '.' {
    35  				hi--
    36  			}
    37  
    38  			// Wildcard was the leftmost part and we have walked the entire host,
    39  			// success.
    40  			if mi == 0 && hi == 0 {
    41  				return true
    42  			}
    43  
    44  			continue
    45  		}
    46  
    47  		if host[hi] != match[mi] {
    48  			return false
    49  		}
    50  
    51  		// We have walked the entire host, if we have not walked the entire matcher
    52  		// (mi != 0) that means the matcher has remaining characters to match and
    53  		// thus the host cannot match.
    54  		if hi == 0 {
    55  			return mi == 0
    56  		}
    57  
    58  		hi--
    59  	}
    60  
    61  	// We have walked the entire length of the matcher, but haven't finished
    62  	// walking the host thus they cannot match.
    63  	return false
    64  }