【发布时间】:2022-01-12 01:57:07
【问题描述】:
我的应用程序运行一个 HTTP 服务器,它提供一些静态文件。大多数文件都可以在/static/ 下访问,但有些文件(例如index.html)必须在根目录下才能访问。
此代码尝试通过将文件嵌入embed.FS 来实现这一点(为了演示,我只在此处嵌入index.html):
package main
import (
"net/http"
"embed"
"io/fs"
"log"
)
//go:embed index.html
var files embed.FS
type primaryFiles struct {}
func (pf *primaryFiles) Open(name string) (fs.File, error) {
// name will be "." for paths / and /index.html, I guess that's a feature
if name == "." {
return files.Open("index.html")
}
return nil, fs.ErrNotExist
}
func main() {
http.Handle("/", http.FileServer(http.FS(&primaryFiles{})))
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(files))))
log.Fatal(http.ListenAndServe(":8080", nil))
}
现在在运行代码时,我可以在http://localhost:8080/static/ 和http://localhost:8080/static/index.html 上查询index.html。但是,在http://localhost:8080/ 和http://localhost:8080/index.html,浏览器会给我ERR_TOO_MANY_REDIRECTS。为什么会这样?我该如何解决?
我已经尝试过传递".",它会生成一个文件列表而不是index.html 内容。我在go version go1.17.3 darwin/arm64。我还试图弄清楚curl 发生了什么:
$ curl -v http://localhost:8080/index.html
* Trying ::1:8080...
* Connected to localhost (::1) port 8080 (#0)
> GET /index.html HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.77.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 301 Moved Permanently
< Location: ./
< Date: Mon, 06 Dec 2021 22:05:50 GMT
< Content-Length: 0
<
* Connection #0 to host localhost left intact
$ curl -v http://localhost:8080/
* Trying ::1:8080...
* Connected to localhost (::1) port 8080 (#0)
> GET / HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.77.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 301 Moved Permanently
< Location: ..//
< Date: Mon, 06 Dec 2021 22:05:12 GMT
< Content-Length: 0
<
* Connection #0 to host localhost left intact
这并不能帮助我理解正在发生的事情——好吧。 /index.html 被重定向到./,这似乎是有道理的。但是/ 被重定向到..//……我不知道该怎么做。
【问题讨论】: