我有一个简单的文件夹:
Test/
main.go
Images/
image1.png
image2.png
index.html在main main.go中,我刚刚指出:
package main
import (
"net/http"
)
func main(){
fs := http.FileServer(http.Dir("./Images"))
http.Handle("/Images/*", fs)
http.ListenAndServe(":3003", nil)
}但是,当我在http://localhost:3003/Images/上滚动,甚至添加到path文件的名称时,它就不能工作了。我不明白,因为这和这门学科上的回复是一样的
你能告诉我这样不行吗?
发布于 2016-09-11 21:49:16
您需要删除*并添加额外的子文件夹Images。
这样做很好:
Test/
main.go
Images/
Images/
image1.png
image2.png
index.html代码:
package main
import (
"net/http"
)
func main() {
fs := http.FileServer(http.Dir("./Images"))
http.Handle("/Images/", fs)
http.ListenAndServe(":3003", nil)
}然后是go run main.go
和:
http://localhost:3003/Images/
或者简单地使用:
package main
import (
"net/http"
)
func main() {
fs := http.FileServer(http.Dir("./Images"))
http.Handle("/", fs)
http.ListenAndServe(":3003", nil)
}与:http://localhost:3003/
发布于 2016-09-12 01:22:37
请求未能返回您预期的结果是因为它们与http.Handle(pattern string, handler Handler)调用中定义的模式不匹配。ServeMux文档提供了关于如何组合模式的描述。任何请求都有前缀,从最特定的到最不特定的匹配。似乎您已经假定可以使用glob模式。对/Images/*<file system path>的请求将调用您的处理程序。您需要像这样定义一个目录路径,Images/。
另外,值得考虑的是,程序是如何从目录路径中获得文件服务的。硬编码相对意味着您的程序将只在文件系统中的特定位置工作,而该位置非常脆弱。您可以使用命令行参数来允许用户指定路径或使用运行时解析的配置文件。这些注意事项使您的程序易于模块化和测试。
发布于 2016-09-11 21:26:10
./Image中的点引用cwd当前工作目录,而不是项目根目录。要使服务器工作,必须从Test/目录运行它,或者使用具有绝对根路径的address映像运行。
https://stackoverflow.com/questions/39440634
复制相似问题