gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:58:17 26 4
gpt4 key购买 nike

尝试使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com