gorilla 多路复用器排除扩展请求

标签 go gorilla

尝试使用 github.com/gorilla/mux 配置 go 服务器路由以响应所有带有 index.html 的请求,但排除扩展名为 .jpg|.js|.png 的请求

由于扩展名而被排除的静态文件将被路由到文件服务器。配置。

尝试失败

  func main() {
        r := mux.NewRouter()

        r.HandleFunc("/{path:^.*([!js|jpg|png|gif])$}", func(w http.ResponseWriter, r *http.Request) {
            http.ServeFile(w, r, "dist/index.html")
        })

        r.PathPrefix("/").Handler(http.StripPrefix("/", http.FileServer(http.Dir("dist"))))

        http.Handle("/", r)
        http.ListenAndServe(":8000", nil)
    }

最佳答案

欢迎更好的方法,希望使用正则表达式,这样事情就完好无损,没有疯狂的 if/else 条件

func main() {
    r := mux.NewRouter()

    r.HandleFunc("/{path:.*}", func(w http.ResponseWriter, r *http.Request) {
        if HasSuffix(r.URL.Path, []string{"js", "css", "gif", "jpeg", "woff2", "woff", "ttf"}) == false {
            fmt.Println("serving index")
            http.ServeFile(w, r, "dist/index.html")
        } else {
            http.ServeFile(w, r, "dist/"+r.URL.Path)
        }
    })

    //r.PathPrefix("/").Handler(http.StripPrefix("/", http.FileServer(http.Dir("dist"))))

    http.Handle("/", r)
    http.ListenAndServe(":8000", nil)
}

//HasSuffix check if url has suffix
func HasSuffix(path string, parts []string) bool {
    for _, part := range parts {
        fmt.Println("checking if part:" + part + " exists in path:" + path)
        if strings.HasSuffix(path, part) == true {
            return true
        }
    }
    return false
}

关于 gorilla 多路复用器排除扩展请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41910294/

相关文章:

go - 如何制作 goreleaser 脚本以在本地构建 deb 文件?

json - Golang map : How to strip out empty fields automatically

go - 如何允许CORS使用多个端口?

go - 成功的websocket连接后如何使发送消息到特定的URL?

session - 戈朗 : Retrieving Gorilla/Sessions Cookie

go - 在golang中将控制信号转换为字节ascii十六进制代码

Go protobuf无法识别相同的包

go - 在 Go 中使用外部 API 后使用 REST 客户端保存数据

go - 运行简单的 cgo 文件时遇到错误

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