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

Fix:middleware matching error 修复中间件匹配错误 #77

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

AimTao
Copy link

@AimTao AimTao commented Sep 15, 2023

gee-web/day5-middleware

背景

比如,我有三个路由地址:

  • /user/id
  • /user/task
  • /username

其中,/user 是一个 RouterGroup,上面配置了一个中间件 logger。

问题

当我访问 /username 时,它并不属于 /user group,但也会匹配到这个中间件。

原因

ServeHTTP 中的这个判断,会判断 /username 包含 /user。

if strings.HasPrefix(req.URL.Path, group.prefix) {

修正

不直接使用 group.prefix,而使用 group.prefix + "/" 进行匹配。
因为我们路径是按照 "/" 来分隔的,这样处理不会先出现误匹配的情况。


PS:看了一下 gin 的实现,对于中间件的匹配,是在 addRoute 时处理的,并将中间件保存在 Router 的 map 中。
这样既可以避免查找,也有利于提升处理请求的性能,大家可以参考。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant