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

静态文件 index.html 404 #9

Closed
xmx opened this issue Sep 8, 2022 · 2 comments
Closed

静态文件 index.html 404 #9

xmx opened this issue Sep 8, 2022 · 2 comments

Comments

@xmx
Copy link
Contributor

xmx commented Sep 8, 2022

目录文件布局如下

.
├─main.go
└─webui
  └─index.html

main.go 内容如下:

package main

import "github.com/xgfone/ship/v5"

func main() {
	s := ship.Default()
	s.Route("/webui").Static("webui") // 只有注册的路由是 / 时 index.html 才正常访问
	ship.StartServer(":8080", s)
}

webui/index.html 内容如下:

<h1>Hello Ship</h1>

结果

访问 http://127.0.0.1:8080/webui 报 404

访问 http://127.0.0.1:8080/webui/index.html 依然报 404

原因分析

注册静态文件路由时,调用 s.Route("/webui").Static("webui") ship 会注册两个路由GET /webui/*pathHEAD /webui/*path

当浏览器访问 GET /webui/index.htmlhttp.FileServer 会将 index.html 的结尾的Path重定向到 ./ ,即:将 GET /webui/index.html 重定向到 GET /webui/ ,而 /webui/ 无法命中 /webui/*path,导致 index.html 404

@xmx
Copy link
Contributor Author

xmx commented Sep 8, 2022

我觉得 /path/* 是可以匹配到 /path/path/,比如在正则中,* 就认为是可以匹配到零个或多个,在 gin 路由中,* 也是可以匹配零个或多个

@xgfone
Copy link
Owner

xgfone commented Sep 9, 2022

这是因为:

  1. Static 在底层使用 http.FileServer 来服务一个目录(如 ./webui),如果访问路径以 /index.html 结尾,则会重定向请求到 ./(如:相当于 /webui/);
  2. ship.Default() 创建的默认路由器启用了 移除请求路径后缀 /,导致重定向后的请求在执行路由查找时变成了 /webui
  3. Static 在注册时,将 Path 路径注册为 Path + "/*"(如 /webui/*),由于中间缺少一个 /,因此无法匹配路由。

解决办法有两个:

  1. ship.Default() 创建新的路由器后,重新设置 Router,如:s.Router = echo.NewRouter(&echo.Config{RemoveTrailingSlash: false})s.Router = echo.NewRouter(nil).
  2. 升配版本到 v5.1.4,如 require github.com/xgfone/ship/v5 v5.1.4.

@xmx xmx closed this as completed Sep 14, 2022
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

No branches or pull requests

2 participants