minor improvement of the context.HandlerName

This commit is contained in:
Gerasimos (Makis) Maropoulos 2024-01-22 15:35:09 +02:00
parent 66e3c26efe
commit ddda4f6998
No known key found for this signature in database
GPG Key ID: B9839E9CD30B7B6B

View File

@ -65,6 +65,7 @@ func SetHandlerName(original string, replacement string) {
regex, _ := regexp.Compile(original)
handlerNames[&NameExpr{
literal: original,
normalizedLiteral: normalizeExpression(original),
regex: regex,
}] = replacement
@ -75,6 +76,7 @@ func SetHandlerName(original string, replacement string) {
type NameExpr struct {
regex *regexp.Regexp
literal string
normalizedLiteral string
}
// MatchString reports whether "s" is literal of "literal"
@ -91,6 +93,23 @@ func (expr *NameExpr) MatchString(s string) bool {
return false
}
// MatchFilename reports whether "filename" contains the "literal".
func (expr *NameExpr) MatchFilename(filename string) bool {
if filename == "" {
return false
}
return strings.Contains(filename, expr.normalizedLiteral)
}
// The regular expression to match the versioning and the domain part
var trimFileModuleNameRegex = regexp.MustCompile(`^[\w.]+/(kataras|iris-contrib)/|/v\d+|\.\*`)
func normalizeExpression(str string) string {
// Replace all occurrences of the regular expression with the replacement string.
return strings.ToLower(trimFileModuleNameRegex.ReplaceAllString(str, ""))
}
// A Handler responds to an HTTP request.
// It writes reply headers and data to the Context.ResponseWriter() and then return.
// Returning signals that the request is finished;
@ -125,11 +144,14 @@ func valueOf(v interface{}) reflect.Value {
// See `SetHandlerName` too.
func HandlerName(h interface{}) string {
pc := valueOf(h).Pointer()
name := runtime.FuncForPC(pc).Name()
fn := runtime.FuncForPC(pc)
name := fn.Name()
filename, _ := fn.FileLine(fn.Entry())
filenameLower := strings.ToLower(filename)
handlerNamesMu.RLock()
for expr, newName := range handlerNames {
if expr.MatchString(name) {
if expr.MatchString(name) || expr.MatchFilename(filenameLower) {
name = newName
break
}