英文:
How to set Home page and static files in same path
问题
如果我运行URL http://localhost:8080/,我想要运行Index函数。如果我运行http://localhost:8080/robot.txt,它应该显示static文件夹中的文件。
func main() {
http.HandleFunc("/", Index)
http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("static"))))
http.ListenAndServe(":8080", nil)
}
func Index(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Index")
}
如何实现这个功能?
目前,我遇到了以下错误:
panic: http: multiple registrations for /
这是我的目录结构:
main.go
static\
| robot.txt
| favicon.ico
| sitemap.xml
英文:
if I run the URL http://localhost:8080/ I want to run the Index function and If I run http://localhost:8080/robot.txt it should show static folder files
func main() {
http.HandleFunc("/", Index)
http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("static"))))
http.ListenAndServe(":8080", nil)
}
func Index(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Index")
}
How to do this.
Currently, I'm getting this error
> panic: http: multiple registrations for /
This is my directory structure
main.go
static\
| robot.txt
| favicon.ico
| sitemap.xml
答案1
得分: 2
将索引处理程序委托给文件服务器:
func main() {
http.HandleFunc("/", Index)
http.ListenAndServe(":8080", nil)
}
var fserve = http.StripPrefix("/", http.FileServer(http.Dir("static"))))
func Index(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
fserve.ServeHTTP(w, r)
return
}
fmt.Fprintln(w, "Index")
}
将上述代码翻译为中文如下:
func main() {
http.HandleFunc("/", Index)
http.ListenAndServe(":8080", nil)
}
var fserve = http.StripPrefix("/", http.FileServer(http.Dir("static"))))
func Index(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
fserve.ServeHTTP(w, r)
return
}
fmt.Fprintln(w, "Index")
}
英文:
Delegate to the file server from the index handler:
func main() {
http.HandleFunc("/", Index)
http.ListenAndServe(":8080", nil)
}
var fserve = http.StripPrefix("/", http.FileServer(http.Dir("static"))))
func Index(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != “/“ {
fserve.ServeHTTP(w, r)
return
}
fmt.Fprintln(w, "Index")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论