go - 提供静态内容并处理 404 not found with Gorilla toolkit

标签 go gorilla

我最近询问了有关使用 Gorilla mux 提供静态内容和处理 404 的问题;当使用 Handle 而不是 PathPrefix 时,应用程序可以提供根页面 ( http://localhost:8888 ):

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/myService", ServiceHandler)
    r.Handle("/", http.FileServer(http.Dir("./static")))
    r.NotFoundHandler = http.HandlerFunc(notFound)
    l, _ := net.Listen("tcp", "8888")
    http.Serve(l, r)
}

然而,对根页面中页面的请求(例如 http://localhost:8888/demo/page1.html )会被 404 处理程序拦截。有什么办法可以防止这种情况,同时捕获对不存在的页面或服务的请求?这是目录结构:

...
main.go
static\
  | index.html
  demo\
    page1.html
    demo.js
    demo.css
    | jquery\
       | <js files>
    | images\
       | <png files>

上一个问题:

我正在使用 Gorilla mux 工具包来处理 Web 服务器应用程序中的 http 请求:

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/myService", ServiceHandler)
    r.PathPrefix("/").Handler(http.FileServer(http.Dir("./static")))
    l, _ := net.Listen("tcp", "8888")
    http.Serve(l, r)
}

我想为无效的 URL 添加一个处理程序,但它从未被调用过:

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/myService", ServiceHandler)
    r.NotFoundHandler = http.HandlerFunc(notFound)
    r.PathPrefix("/").Handler(http.FileServer(http.Dir("static")))
    l, _ := net.Listen("tcp", "8888")
    http.Serve(l, r)
}

如果我删除静态处理程序,将调用未找到的处理程序。但是,应用程序需要从非绝对路径提供静态内容。有没有办法将其与 404 处理结合起来?

最佳答案

我怀疑 r.PathPrefix("/").Handler() 会匹配任何路径,从而使 notfound 处理程序无用。

如“route.go”中所述:

// Note that it does not treat slashes specially 
// ("`/foobar/`" will be matched by the prefix "`/foo`") 
// so you may want to use a trailing slash here.

如果您使用 PathPrefix(如 those tests ),请将其用于特定路径,而不是通用的“/”。

关于go - 提供静态内容并处理 404 not found with Gorilla toolkit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30052002/

相关文章:

go - 如何管理 Web 应用程序中的长进程

go - 如何设置 gorilla /websocket 连接以充当浏览器应用程序的 JSON-RPC 客户端?

go - 如何在中间件中获取路由参数?

linux - Go、sudo 和 apache 端口 80

golang 在指定路径返回静态 html 文件

go - 为什么 Go 中的 math.Nextafter(2,3) 递增 0.0000000000000004 而不是 0.0000000000000001?

go - 如何使用 golang 在 WebDAV 中实现基本身份验证?

go - 将go命令作为gradle任务运行

go - 优化排序周期列表的迭代

templates - 如何用逗号连接领事模板的服务元数据