2

如果我运行 URL http://localhost:8080/ 我想运行 Index 函数,如果我运行 http://localhost:8080/robot.txt 它应该显示静态文件夹文件

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")
}

这个怎么做。

目前,我收到此错误

恐慌:http:多次注册/

这是我的目录结构

main.go
static\
  | robot.txt
  | favicon.ico
  | sitemap.xml
4

1 回答 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")
}
于 2021-12-18T20:09:42.417 回答