当在Negroni下找不到路由时,提供索引文件。

huangapple go评论103阅读模式
英文:

Serving index file when route not found under Negroni

问题

我正在使用Golang、Negroni和Gorilla mux构建一个Web API服务器。我的API路由位于/api下,我使用Negroni来从/public目录下的URL中提供静态文件。我希望不仅在请求名称或作为索引文件时提供index.html文件(包含单页JavaScript应用程序),而且在请求否则会导致404错误的情况下也提供该文件,因为它不对应于路由或/public目录中的文件。这样,这些URL将加载Web应用程序,该应用程序将转到正确的路由(客户端JavaScript历史记录/推送状态),否则如果资源不存在,则会显示未找到错误。是否有办法让Negroni的静态中间件或Gorilla mux实现这一点?

英文:

I am using Golang, Negroni, and Gorilla mux for a web api server. I have my api routes under /api and I am using Negroni to serve static files from my /public directory using urls under /. I would like to serve my index.html file (containing a single page javascript application) not only if it is requested by name or as the index file, but also if the request would otherwise result in a 404 because it doesn't correspond to a route or a file in the /public directory. This is so that those URLs will load the webapp which will transition to the correct route (client side javascript history/pushState) or else give a not found error if that resource doesn't exist. Is there a way to get Negroni's static middleware or Gorilla mux to do this?

答案1

得分: 4

在mux库中,Router类型具有一个NotFoundHandler字段,其类型为http.Handler。这将允许您根据需要处理未匹配的路由:

// NotFoundHandler覆盖默认的未找到处理程序
func NotFoundHandler(w http.ResponseWriter, r *http.Request) {
    // 您可以使用serve file助手来响应404请求
    http.ServeFile(w, r, "public/index.html")
}

func main() {
    r := mux.NewRouter()
    r.NotFoundHandler = http.HandlerFunc(NotFoundHandler)
    
    // 注册其他路由或设置negroni

    log.Fatal(http.ListenAndServe(":8080", r))
}

以上是代码的翻译部分。

英文:

The Router type in the mux library has a NotFoundHandler field of type http.Handler. This would allow you to handle a unmatched route as you see fit:

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

huangapple
  • 本文由 发表于 2015年11月1日 01:21:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/33454383.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定