英文:
Where does Go web server look for the files
问题
我有一个简单的网页应用程序,代码文件名为HttpServer.go:
package main
import (
"net/http"
)
func main() {
mux := http.NewServeMux()
files := http.FileServer(http.Dir("/public"))
mux.Handle("/static/", http.StripPrefix("/static/", files))
server := &http.Server{
Addr: "localhost:8080",
Handler: mux,
}
server.ListenAndServe()
}
我将这个代码文件放在%GOPATH%/src/first_app目录下,并使用go install
命令安装了这个程序,first_app.exe
出现在%GOPATH%/bin目录中。
当我启动web服务器后,我访问了http://localhost:8080/static/a.txt,但是出现了404(未找到)
的错误,提示找不到a.txt文件。
我想问一下,我应该把public
目录和a.txt
文件放在哪里?
英文:
I have a simple web application, the code file which is named HttpServer.go is:
package main
import (
"net/http"
)
func main() {
mux := http.NewServeMux()
files := http.FileServer(http.Dir("/public"))
mux.Handle("/static/", http.StripPrefix("/static/", files))
server := &http.Server{
Addr: "localhost:8080",
Handler: mux,
}
server.ListenAndServe()
}
I have put the this code file under %GOPATH%/src/first_app, and I go install
this program, the first_app.exe
shows up in %GOPATH%/bin
When I startup the webserver,I accessed
http://localhost:8080/static/a.txt, but 404(NOT FOUND)
complains that a.txt is not found.,
I would ask where should I put the directory public and a.txt
答案1
得分: 1
根据你在http.Dir
表达式中指定的路径查找。在你的情况下是/public
。
很可能你的系统上没有名为/public
的路径(因为这是我熟悉的所有操作系统中的非标准目录路径,我猜你还没有创建它)。
将/public
更改为与你放置文件的路径匹配。
英文:
It looks in the path you specify in your http.Dir
expression. /public
in your case.
Most likely you don't have a path called /public
on your system (since this is a non-standard directory path on all OSes I'm familiar with, and I suspect you haven't created it).
Change /public
to match the path where you put your files.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论