Golang中http.Dir的工作原理是什么?
Golang中http.Dir的工作原理是什么?
http.Handle("/assets", http.FileServer(http.Dir(".")))
这将返回我assets文件夹内的所有内容作为响应。而当我这样做时:
http.Handle("/assets", http.FileServer(http.Dir("/files")))
为什么它不返回assets文件夹内的所有文件?
2 回复
第一种变体会从当前工作目录提供所有内容,它与资源文件夹或搜索该文件夹无关。
后者从文件系统根目录开始搜索 /files 路径。
这正是在大多数操作系统中相对路径和绝对路径的通用工作方式。
更多关于Golang中http.Dir的工作原理是什么?的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
在Go语言中,http.Dir类型实现了http.FileSystem接口,用于提供对文件系统的访问。关键在于理解http.FileServer如何处理请求路径与文件系统路径的映射关系。
当使用http.FileServer(http.Dir("."))并注册到/assets路径时:
- 请求路径
/assets/foo.txt会被转换为文件系统路径./assets/foo.txt - 这是因为
http.FileServer会从请求路径中去除注册的前缀/assets,然后将剩余部分附加到http.Dir指定的根目录
在你的第二个例子中:
http.Handle("/assets", http.FileServer(http.Dir("/files")))
- 请求路径
/assets/foo.txt会被转换为文件系统路径/files/foo.txt - 注意:这里去除了前缀
/assets,只剩下foo.txt,然后附加到/files/目录下 - 所以它会在
/files目录下查找foo.txt,而不是在/files/assets目录下
如果你想要正确映射,应该这样配置:
// 方法1:修改文件系统根目录
http.Handle("/assets/", http.FileServer(http.Dir("/files/assets")))
// 方法2:使用StripPrefix
http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("/files"))))
示例代码演示:
package main
import (
"net/http"
)
func main() {
// 正确的方式1:文件系统根目录包含assets文件夹
http.Handle("/assets/", http.FileServer(http.Dir("/files/assets")))
// 正确的方式2:使用StripPrefix移除URL前缀
http.Handle("/assets/", http.StripPrefix("/assets/",
http.FileServer(http.Dir("/files"))))
http.ListenAndServe(":8080", nil)
}
关键点:
http.FileServer会自动去除URL路径中与注册路径匹配的前缀- 剩余路径会直接附加到
http.Dir指定的根目录 - 注意注册路径应该以
/结尾,这样能正确处理子路径请求

