Repository: cloudwego/hertz
Pull request #232 (2022-09-06 14:31:35)

fix: fix some tsr bugs
#### What type of PR is this?
<!--
Add one of the following kinds:

build: Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm)
ci: Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs)
docs: Documentation only changes
feat: A new feature
optimize: A new optimization
fix: A bug fix
perf: A code change that improves performance
refactor: A code change that neither fixes a bug nor adds a feature
style: Changes that do not affect the meaning of the code (white space, formatting, missing semi-colons, etc)
test: Adding missing tests or correcting existing tests
chore: Changes to the build process or auxiliary tools and libraries such as documentation generation
-->
fix: A bug fix
#### Check the PR title.
<!--
The description of the title will be attached in Release Notes, 
so please describe it from user-oriented, what this PR does / why we need it.
Please check your PR title with the below requirements:
-->
- [x] This PR title match the format: \<type\>(optional scope): \<description\>
- [x] The description of this PR title is user-oriented and clear enough for others to understand.


#### (Optional) Translate the PR title into Chinese.
修复一些tsr参数返回错误的bug

#### (Optional) More detail description for this PR(en: English/zh: Chinese).
<!--
Provide more detailed info for review. If it is a perf type PR, perf data is suggested to give.
-->
en: 1.Registering the route "/a/:b/*c", then request the path "/a/b", the find function in tree.go will return a false tsr so that server return 404 page not found.
2.Registering the route "/aa" and "/a/*b", then request the path "/a", the find function will return a false tsr
3.There's something wrong with the if conditional logic
![image](https://user-images.githubusercontent.com/45221305/188773334-a11623f5-7137-4503-93df-bf3d86f6ba9c.png)

zh(optional):1.注册"/a/:b/*c"路由，然后发起请求访问/a/b，文件tree.go中find函数会返回一个false的tsr导致无法自动重定向，因此服务端返回了404
2.同时注册"/aa"和"/a/*b", 然后发起请求访问/a，find函数返回false的tsr
3.在上图的if判断语句中存在一些逻辑错误，因为代码走到这的时候search和cn.prefix的前缀并不一定相等

#### Which issue(s) this PR fixes:
<!--
Automatically closes linked issue when PR is merged.
Eg: `Fixes #<issue number>`, or `Fixes (paste link of issue)`.
-->
Fixes [#231](https://github.com/cloudwego/hertz/issues/231)

CLAassistant: [![CLA assistant check](https://cla-assistant.io/pull/badge/not_signed)](https://cla-assistant.io/cloudwego/hertz?pullRequest=232) <br/>Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our [Contributor License Agreement](https://cla-assistant.io/cloudwego/hertz?pullRequest=232) before we can accept your contribution.<br/><hr/>**hushengquan** seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please [add the email address used for this commit to your account](https://help.github.com/articles/why-are-my-commits-linked-to-the-wrong-user/#commits-are-not-linked-to-any-user).<br/><sub>You have signed the CLA already but the status is still pending? Let us [recheck](https://cla-assistant.io/check/cloudwego/hertz?pullRequest=232) it.</sub>
codecov[bot]: # [Codecov](https://codecov.io/gh/cloudwego/hertz/pull/232?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=cloudwego) Report
> Merging [#232](https://codecov.io/gh/cloudwego/hertz/pull/232?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=cloudwego) (92b3038) into [develop](https://codecov.io/gh/cloudwego/hertz/commit/87516089fd86dcf997779fc8c05b233710ec3dc0?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=cloudwego) (8751608) will **decrease** coverage by `0.09%`.
> The diff coverage is `100.00%`.

> :exclamation: Current head 92b3038 differs from pull request most recent head 80478ef. Consider uploading reports for the commit 80478ef to get more accurate results

```diff
@@             Coverage Diff             @@
##           develop     #232      +/-   ##
===========================================
- Coverage    59.19%   59.10%   -0.10%     
===========================================
  Files           79       79              
  Lines         8105     8104       -1     
===========================================
- Hits          4798     4790       -8     
- Misses        2953     2960       +7     
  Partials       354      354              
```


| [Impacted Files](https://codecov.io/gh/cloudwego/hertz/pull/232?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=cloudwego) | Coverage Δ | |
|---|---|---|
| [pkg/route/tree.go](https://codecov.io/gh/cloudwego/hertz/pull/232/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=cloudwego#diff-cGtnL3JvdXRlL3RyZWUuZ28=) | `96.66% <100.00%> (ø)` | |
| [pkg/common/timer/timer.go](https://codecov.io/gh/cloudwego/hertz/pull/232/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=cloudwego#diff-cGtnL2NvbW1vbi90aW1lci90aW1lci5nbw==) | `61.90% <0.00%> (-19.05%)` | :arrow_down: |
| [pkg/common/compress/compress.go](https://codecov.io/gh/cloudwego/hertz/pull/232/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=cloudwego#diff-cGtnL2NvbW1vbi9jb21wcmVzcy9jb21wcmVzcy5nbw==) | `80.95% <0.00%> (-2.86%)` | :arrow_down: |
| [pkg/network/standard/buffer.go](https://codecov.io/gh/cloudwego/hertz/pull/232/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=cloudwego#diff-cGtnL25ldHdvcmsvc3RhbmRhcmQvYnVmZmVyLmdv) | `81.08% <0.00%> (-0.50%)` | :arrow_down: |

Help us with your feedback. Take ten seconds to tell us [how you rate us](https://about.codecov.io/nps?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=cloudwego). Have a feature suggestion? [Share it here.](https://app.codecov.io/gh/feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=cloudwego)


Patch:
diff --git a/go.mod b/go.mod
index 7f9b9b5..cf0ca35 100644
--- a/go.mod
+++ b/go.mod
@@ -6,7 +6,7 @@ require (
 	github.com/bytedance/go-tagexpr/v2 v2.9.2
 	github.com/bytedance/gopkg v0.0.0-20220413063733-65bf48ffb3a7
 	github.com/bytedance/sonic v1.3.5
-	github.com/cloudwego/netpoll v0.2.4
+	github.com/cloudwego/netpoll v0.2.6
 	github.com/fsnotify/fsnotify v1.5.4
 	golang.org/x/sync v0.0.0-20210220032951-036812b2e83c
 	golang.org/x/sys v0.0.0-20220412211240-33da011f77ad
diff --git a/go.sum b/go.sum
index 4ec04ce..1ed067c 100644
--- a/go.sum
+++ b/go.sum
@@ -2,14 +2,12 @@ github.com/bytedance/go-tagexpr/v2 v2.9.2 h1:QySJaAIQgOEDQBLS3x9BxOWrnhqu5sQ+f6H
 github.com/bytedance/go-tagexpr/v2 v2.9.2/go.mod h1:5qsx05dYOiUXOUgnQ7w3Oz8BYs2qtM/bJokdLb79wRM=
 github.com/bytedance/gopkg v0.0.0-20220413063733-65bf48ffb3a7 h1:PtwsQyQJGxf8iaPptPNaduEIu9BnrNms+pcRdHAxZaM=
 github.com/bytedance/gopkg v0.0.0-20220413063733-65bf48ffb3a7/go.mod h1:2ZlV9BaUH4+NXIBF0aMdKKAnHTzqH+iMU4KUjAbL23Q=
-github.com/bytedance/sonic v1.3.0 h1:T2rlvNytw6bTmczlAXvGqmuMzIqGJBOsJKYwRPWR7Y8=
-github.com/bytedance/sonic v1.3.0/go.mod h1:V973WhNhGmvHxW6nQmsHEfHaoU9F3zTF+93rH03hcUQ=
 github.com/bytedance/sonic v1.3.5 h1:xfBNhsG3QCC+AMCmCHxNQg0StI5IM/B9Jtwjqi5WlI0=
 github.com/bytedance/sonic v1.3.5/go.mod h1:V973WhNhGmvHxW6nQmsHEfHaoU9F3zTF+93rH03hcUQ=
 github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06 h1:1sDoSuDPWzhkdzNVxCxtIaKiAe96ESVPv8coGwc1gZ4=
 github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=
-github.com/cloudwego/netpoll v0.2.4 h1:Kbo2HA1cXEgoy/bu1jSNrjcqZj2diENcJqLy6vKiROU=
-github.com/cloudwego/netpoll v0.2.4/go.mod h1:1T2WVuQ+MQw6h6DpE45MohSvDTKdy2DlzCx2KsnPI4E=
+github.com/cloudwego/netpoll v0.2.6 h1:vzN8cyayoa9RdCOG87tqkYO/j2hA4SMLC+vkcNUq6uI=
+github.com/cloudwego/netpoll v0.2.6/go.mod h1:1T2WVuQ+MQw6h6DpE45MohSvDTKdy2DlzCx2KsnPI4E=
 github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
 github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
 github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
diff --git a/pkg/route/tree.go b/pkg/route/tree.go
index 774c8a3..4c2d9de 100644
--- a/pkg/route/tree.go
+++ b/pkg/route/tree.go
@@ -361,7 +361,8 @@ func (r *router) find(path string, paramsPointer *param.Params, unescape bool) (
 				searchIndex = searchIndex + len(cn.prefix)
 			} else {
 				// not equal
-				if (len(cn.prefix) == len(search)+1) && (cn.prefix[len(search)]) == '/' && (cn.handlers != nil || cn.anyChild != nil) {
+				if (len(cn.prefix) == len(search)+1) &&
+					(cn.prefix[len(search)]) == '/' && cn.prefix[:len(search)] == search && (cn.handlers != nil || cn.anyChild != nil) {
 					res.tsr = true
 				}
 				// No matching prefix, let's backtrack to the first possible alternative node of the decision path
@@ -394,7 +395,7 @@ func (r *router) find(path string, paramsPointer *param.Params, unescape bool) (
 		}
 
 		if search == nilString {
-			if cd := cn.findChild('/'); cd != nil && cd.handlers != nil {
+			if cd := cn.findChild('/'); cd != nil && (cd.handlers != nil || cd.anyChild != nil) {
 				res.tsr = true
 			}
 		}
@@ -419,7 +420,7 @@ func (r *router) find(path string, paramsPointer *param.Params, unescape bool) (
 			search = search[i:]
 			searchIndex = searchIndex + i
 			if search == nilString {
-				if cd := cn.findChild('/'); cd != nil && cd.handlers != nil {
+				if cd := cn.findChild('/'); cd != nil && (cd.handlers != nil || cd.anyChild != nil) {
 					res.tsr = true
 				}
 			}
diff --git a/version.go b/version.go
index d71e454..8119d30 100644
--- a/version.go
+++ b/version.go
@@ -19,5 +19,5 @@ package hertz
 // Name and Version info of this framework, used for statistics and debug
 const (
 	Name    = "Hertz"
-	Version = "v0.3.0"
+	Version = "v0.3.1"
 )


Test patch:
diff --git a/pkg/route/tree_test.go b/pkg/route/tree_test.go
index cdb190b..946bfd6 100644
--- a/pkg/route/tree_test.go
+++ b/pkg/route/tree_test.go
@@ -471,6 +471,14 @@ func TestTreeTrailingSlashRedirect(t *testing.T) {
 		"/no/a",
 		"/no/b",
 		"/api/hello/:name",
+		"/user/:name/*id",
+		"/resource",
+		"/r/*id",
+		"/book/biz/:name",
+		"/book/biz/abc",
+		"/book/biz/abc/bar",
+		"/book/:page/:name",
+		"/book/hello/:name/biz/",
 	}
 	for _, route := range routes {
 		recv := catchPanic(func() {
@@ -496,6 +504,11 @@ func TestTreeTrailingSlashRedirect(t *testing.T) {
 		"/admin/config/",
 		"/admin/config/permissions/",
 		"/doc/",
+		"/user/name",
+		"/r",
+		"/book/hello/a/biz",
+		"/book/biz/foo/",
+		"/book/biz/abc/bar/",
 	}
 	v := make(param.Params, 0, 10)
 	for _, route := range tsrRoutes {
@@ -514,6 +527,10 @@ func TestTreeTrailingSlashRedirect(t *testing.T) {
 		"/_",
 		"/_/",
 		"/api/world/abc",
+		"/book",
+		"/book/",
+		"/book/hello/a/abc",
+		"/book/biz/abc/biz",
 	}
 	for _, route := range noTsrRoutes {
 		value := tree.find(route, &v, false)