github.com/wangyougui/gf/v2@v2.6.5/text/gstr/gstr_domain.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/wangyougui/gf.
     6  
     7  package gstr
     8  
     9  import "strings"
    10  
    11  // IsSubDomain checks whether `subDomain` is sub-domain of mainDomain.
    12  // It supports '*' in `mainDomain`.
    13  func IsSubDomain(subDomain string, mainDomain string) bool {
    14  	if p := strings.IndexByte(subDomain, ':'); p != -1 {
    15  		subDomain = subDomain[0:p]
    16  	}
    17  	if p := strings.IndexByte(mainDomain, ':'); p != -1 {
    18  		mainDomain = mainDomain[0:p]
    19  	}
    20  	var (
    21  		subArray   = strings.Split(subDomain, ".")
    22  		mainArray  = strings.Split(mainDomain, ".")
    23  		subLength  = len(subArray)
    24  		mainLength = len(mainArray)
    25  	)
    26  	// Eg:
    27  	// "goframe.org" is not sub-domain of "s.goframe.org".
    28  	if mainLength > subLength {
    29  		for i := range mainArray[0 : mainLength-subLength] {
    30  			if mainArray[i] != "*" {
    31  				return false
    32  			}
    33  		}
    34  	}
    35  
    36  	// Eg:
    37  	// "s.s.goframe.org" is not sub-domain of "*.goframe.org"
    38  	// but
    39  	// "s.s.goframe.org" is sub-domain of "goframe.org"
    40  	if mainLength > 2 && subLength > mainLength {
    41  		return false
    42  	}
    43  	minLength := subLength
    44  	if mainLength < minLength {
    45  		minLength = mainLength
    46  	}
    47  	for i := minLength; i > 0; i-- {
    48  		if mainArray[mainLength-i] == "*" {
    49  			continue
    50  		}
    51  		if mainArray[mainLength-i] != subArray[subLength-i] {
    52  			return false
    53  		}
    54  	}
    55  	return true
    56  }