【问题标题】:How to set Home page and static files in same path如何在同一路径中设置主页和静态文件
【发布时间】:2021-12-18 20:04:01
【问题描述】:

如果我运行 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

【问题讨论】:

    标签: go go-http


    【解决方案1】:

    从索引处理程序委托给文件服务器:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-21
      • 2019-10-26
      • 1970-01-01
      • 2017-03-24
      • 2020-01-04
      • 2020-10-23
      • 2013-01-20
      • 1970-01-01
      相关资源
      最近更新 更多