提交kit/utils

Signed-off-by: lixxxww <941403820@qq.com>
This commit is contained in:
lixxxww
2024-01-23 11:57:42 +00:00
committed by Gitee
parent c456d1249e
commit 0ff66b9d43
19 changed files with 1550 additions and 0 deletions

42
kit/utils/regexp.go Normal file
View File

@@ -0,0 +1,42 @@
package utils
import (
"regexp"
"sync"
)
var (
regexMu = sync.RWMutex{}
// Cache for regex object.
// Note that:
// 1. It uses sync.RWMutex ensuring the concurrent safety.
// 2. There's no expiring logic for this map.
regexMap = make(map[string]*regexp.Regexp)
)
// getRegexp returns *regexp.Regexp object with given `pattern`.
// It uses cache to enhance the performance for compiling regular expression pattern,
// which means, it will return the same *regexp.Regexp object with the same regular
// expression pattern.
//
// It is concurrent-safe for multiple goroutines.
func GetRegexp(pattern string) (regex *regexp.Regexp, err error) {
// Retrieve the regular expression object using reading lock.
regexMu.RLock()
regex = regexMap[pattern]
regexMu.RUnlock()
if regex != nil {
return
}
// If it does not exist in the cache,
// it compiles the pattern and creates one.
regex, err = regexp.Compile(pattern)
if err != nil {
return
}
// Cache the result object using writing lock.
regexMu.Lock()
regexMap[pattern] = regex
regexMu.Unlock()
return
}