【问题标题】:Serving static html using Gorilla mux使用 Gorilla mux 提供静态 html
【发布时间】:2017-10-30 21:56:21
【问题描述】:

我正在使用 gorilla serve mux 来提供静态 html 文件。

r := mux.NewRouter()
r.PathPrefix("/").Handler(http.FileServer(http.Dir("./public"))).Methods("GET")

我在公共文件夹中确实有一个 Index.html 文件以及其他 html 文件。

浏览网站时,我得到文件夹的所有内容,而不是默认的 Index.html。

我来自 C#,我知道 IIS 将 Index.html 作为默认值,但可以选择任何页面作为默认值。

我想知道是否有适当的方法来选择默认页面以在 Gorilla mux 中提供服务,而无需创建自定义处理程序/包装器。

【问题讨论】:

  • 我不认为这是因为 Gorilla 多路复用器,而是因为 http.FileServer,在 docs 中它说 As a special case, the returned file server redirects any request ending in "/index.html" to the same path, without the final "index.html".
  • 老兄,你应该把它作为答案发布,因为你解决了它!

标签: html go gorilla


【解决方案1】:

也许使用自定义http.HandlerFunc 会更容易:

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    // Here you can check if path is empty, you can render index.html
    http.ServeFile(w, r, r.URL.Path)
})

【讨论】:

    【解决方案2】:

    您必须制作自定义处理程序,因为您需要自定义行为。在这里,我只是包装了http.FileServer 处理程序。

    试试这个:

    package main
    
    import (
        "log"
        "net/http"
    
        "github.com/gorilla/mux"
    )
    
    func main() {
    
        handler := mux.NewRouter()
    
        fs := http.FileServer(http.Dir("./public"))
        handler.PathPrefix("/").Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            if r.URL.Path == "/" {
                //your default page
                r.URL.Path = "/my_default_page.html"
            }
    
            fs.ServeHTTP(w, r)
        })).Methods("GET")
    
        log.Fatal(http.ListenAndServe(":8080", handler))
    }
    

    因此,从代码中,如果访问路径是根 (/),那么您将 r.URL.Path 重写为默认页面,在本例中为 my_default_page.html

    【讨论】:

      【解决方案3】:

      在grabthefish 提到它之后,我决定检查gorilla serve mux 的实际代码。 此代码取自 Gorilla mux 所基于的 net/http 包。

      func serveFile(w ResponseWriter, r *Request, fs FileSystem, name string, 
      redirect bool) {
      const indexPage = "/index.html"
      
      // redirect .../index.html to .../
      // can't use Redirect() because that would make the path absolute,
      // which would be a problem running under StripPrefix
      if strings.HasSuffix(r.URL.Path, indexPage) {
          localRedirect(w, r, "./")
          return
      }
      

      代码请求索引文件为小写的 index.html,因此重命名我的索引文件解决了它。 谢谢你抓鱼!

      【讨论】: