1

我将 Golang、Negroni 和 Gorilla mux 用于 Web api 服务器。我在 /api 下有我的 api 路由,我正在使用 Negroni 使用 / 下的 url 从我的 /public 目录提供静态文件。我想提供我的 index.html 文件(包含单页 javascript 应用程序),不仅是按名称或作为索引文件请求它,而且如果请求会导致 404,因为它不对应/public 目录中的路由或文件。这样一来,这些 URL 将加载 Web 应用程序,该应用程序将转换到正确的路由(客户端 javascript 历史记录/pushState),或者如果该资源不存在,则会给出未找到错误。有没有办法让 Negroni 的静态中间件或 Gorilla mux 做到这一点?

4

1 回答 1

4

Routermux 库中的类型有一个typeNotFoundHandler字段http.Handler。这将允许您处理您认为合适的无与伦比的路线:

// NotFoundHandler overrides the default not found handler
func NotFoundHandler(w http.ResponseWriter, r *http.Request) {
    // You can use the serve file helper to respond to 404 with
    // your request file.

    http.ServeFile(w, r, "public/index.html")
}

func main() {
    r := mux.NewRouter()
    r.NotFoundHandler = http.HandlerFunc(NotFoundHandler)

    // Register other routes or setup negroni

    log.Fatal(http.ListenAndServe(":8080", r))
} 
于 2015-10-31T18:26:09.197 回答