使用 Gorilla mux 提供静态服务 html

Serving static html using Gorilla mux

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

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

我在 public 文件夹中有一个 Index.html 文件以及其他 html 文件。

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

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

我想知道是否有适当的方法 select 在 Gorilla mux 中提供默认页面而无需创建自定义 handler/wrapper。

也许使用自定义 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)
})

您必须创建自定义处理程序,因为您需要自定义行为。在这里,我只是包装了 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.

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

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 小写,因此重命名我的索引文件解决了这个问题。 谢谢抓鱼!