英文:
Serving HTTP Requests and Files using same server in Go Lang
问题
你好,我正在尝试使用Go语言创建一个同时提供文件和HTTP请求的服务器。
我希望"/upload"路径接受POST请求,
"/files"路径在"fpath"中提供静态文件。
我尝试了以下代码,但是出现了404错误:
func main() {
fpath, _ := filepath.Abs(filepath.Dir(os.Args[0]))
fpath+="/public"
fmt.Println(fpath)
http.HandleFunc("/upload",uploadFunc)
http.HandleFunc("/files",http.FileServer(http.Dir(fpath)))
panic(http.ListenAndServe(":8080", nil))
}
请帮我翻译以上内容。
英文:
Hi I am trying to create a server in Go Lang which serves files and HTTP Requests at the same time.
I want <code>/upload</code> path to accept post requests and
<code>/files</code> path to serve static files in the <code>fpath</code>
I tried with the following code but i get a 404 error
func main() {
fpath, _ := filepath.Abs(filepath.Dir(os.Args[0]))
fpath+="/public"
fmt.Println(fpath)
http.HandleFunc("/upload",uploadFunc)
http.HandleFunc("/files",http.FileServer(http.Dir(fpath)))
panic(http.ListenAndServe(":8080", nil))
}
答案1
得分: 3
你需要在处理路径上添加尾部斜杠,如果它是一个目录的话。更多信息请参考http://golang.org/pkg/net/http/#ServeMux。
模式名称固定,根路径,如"/favicon.ico",或者根子树,如"/images/"(注意尾部斜杠)。
尝试一下:
func main() {
fpath, _ := filepath.Abs(filepath.Dir(os.Args[0]))
fpath += "/public"
fmt.Println(fpath)
http.HandleFunc("/upload", uploadFunc)
http.Handle("/files/", http.StripPrefix("/files/", http.FileServer(http.Dir(fpath))))
panic(http.ListenAndServe(":8080", nil))
}
英文:
You need trailing slashes on your handle path if it's a directory. See http://golang.org/pkg/net/http/#ServeMux for more info.
>Patterns name fixed, rooted paths, like "/favicon.ico", or rooted subtrees, like "/images/" (note the trailing slash).
Try
func main() {
fpath, _ := filepath.Abs(filepath.Dir(os.Args[0]))
fpath+="/public"
fmt.Println(fpath)
http.HandleFunc("/upload",uploadFunc)
http.Handle("/files/", http.StripPrefix("/files/", http.FileServer(http.Dir(fpath))))
panic(http.ListenAndServe(":8080", nil))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论