gf/text/gstr/gstr_domain.go
John Guo 7d1a508ea9
improve ut case for package gcache/gpool (#2290)
* improve ut case for package gcache/gpool

* up
2022-11-12 10:49:48 +08:00

57 lines
1.4 KiB
Go

// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gstr
import "strings"
// IsSubDomain checks whether `subDomain` is sub-domain of mainDomain.
// It supports '*' in `mainDomain`.
func IsSubDomain(subDomain string, mainDomain string) bool {
if p := strings.IndexByte(subDomain, ':'); p != -1 {
subDomain = subDomain[0:p]
}
if p := strings.IndexByte(mainDomain, ':'); p != -1 {
mainDomain = mainDomain[0:p]
}
var (
subArray = strings.Split(subDomain, ".")
mainArray = strings.Split(mainDomain, ".")
subLength = len(subArray)
mainLength = len(mainArray)
)
// Eg:
// "goframe.org" is not sub-domain of "s.goframe.org".
if mainLength > subLength {
for i := range mainArray[0 : mainLength-subLength] {
if mainArray[i] != "*" {
return false
}
}
}
// Eg:
// "s.s.goframe.org" is not sub-domain of "*.goframe.org"
// but
// "s.s.goframe.org" is sub-domain of "goframe.org"
if mainLength > 2 && subLength > mainLength {
return false
}
minLength := subLength
if mainLength < minLength {
minLength = mainLength
}
for i := minLength; i > 0; i-- {
if mainArray[mainLength-i] == "*" {
continue
}
if mainArray[mainLength-i] != subArray[subLength-i] {
return false
}
}
return true
}