Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(main): 增加path匹配器 #18

Merged
merged 2 commits into from
Apr 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions example/matcher/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,12 @@ func main() {
context.Next()
})

//添加带路径匹配器的自定义中间件
chain.UseMatcher(matcher.PathPrefix("/hello"), func(context *knife.Context) {
log.Println("pathPrefix matcher")
context.Next()
})

//启动服务
_ = http.ListenAndServe(":8080", chain)
}
41 changes: 41 additions & 0 deletions knife/matcher/path.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// 关于路径的匹配器

package matcher

import (
"fmt"
"knife"
"log"
"regexp"
"strings"
)

// PathPrefix 路径前缀匹配
func PathPrefix(prefix string) knife.MiddlewareMatcher {
return func(response knife.HttpResponseWriter, request knife.HttpRequest) bool {
return strings.HasPrefix(request.URL.Path, prefix)
}
}

// PathMatch 路径正则匹配
func PathMatch(pattern string) knife.MiddlewareMatcher {
return func(response knife.HttpResponseWriter, request knife.HttpRequest) bool {
matched, err := isPathMatched(request.URL.Path, pattern)
if err != nil {
log.Println("path matched failed")
return false
}
return matched
}
}

// isPathMatched 路径匹配方式
// path 路径
// pattern 正则表达式
func isPathMatched(path string, pattern string) (bool, error) {
re, err := regexp.Compile(pattern)
if err != nil {
return false, fmt.Errorf("invalid regular expression: %w", err)
}
return re.MatchString(path), nil
}
Loading