gpt4 book ai didi

go - 当没有路由与 Gorilla 匹配时提供文件?

转载 作者:IT王子 更新时间:2023-10-29 02:04:06 25 4
gpt4 key购买 nike

我使用 Gorilla Mux 作为我的网络服务器。

我定义了一堆路由,但如果没有匹配的路由,我希望它为我的 index.html 文件提供服务。

func (mgr *ApiMgr) InstantiateRestRtr() *mux.Router {
mgr.pRestRtr = mux.NewRouter().StrictSlash(true)
mgr.pRestRtr.PathPrefix("/api/").Handler(http.StripPrefix("/api/",
http.FileServer(http.Dir(mgr.fullPath+"/docsui"))))

for _, route := range mgr.restRoutes {
var handler http.Handler
handler = Logger(route.HandlerFunc, route.Name)
mgr.pRestRtr.Methods(route.Method)
.Path(route.Pattern)
.Name(route.Name)
.Handler(handler)
}

// Here I want to catch any unmatched routes, and serve my '/site/index.html` file.
// How can I do this?

return mgr.pRestRtr
}

最佳答案

您不需要覆盖 404 行为。使用 PathPrefix 作为包罗万象的路由,将其添加到所有其他路由之后。

func main() {
var entry string
var static string
var port string

flag.StringVar(&entry, "entry", "./index.html", "the entrypoint to serve.")
flag.StringVar(&static, "static", ".", "the directory to serve static files from.")
flag.StringVar(&port, "port", "8000", "the `port` to listen on.")
flag.Parse()

r := mux.NewRouter()

// Note: In a larger application, we'd likely extract our route-building logic into our handlers
// package, given the coupling between them.

// It's important that this is before your catch-all route ("/")
api := r.PathPrefix("/api/v1/").Subrouter()
api.HandleFunc("/users", GetUsersHandler).Methods("GET")

// Serve static assets directly.
r.PathPrefix("/dist").Handler(http.FileServer(http.Dir(static)))

// Catch-all: Serve our JavaScript application's entry-point (index.html).
r.PathPrefix("/").HandlerFunc(IndexHandler(entry))

srv := &http.Server{
Handler: handlers.LoggingHandler(os.Stdout, r),
Addr: "127.0.0.1:" + port,
// Good practice: enforce timeouts for servers you create!
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}

log.Fatal(srv.ListenAndServe())
}

func IndexHandler(entrypoint string) func(w http.ResponseWriter, r *http.Request) {
fn := func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, entrypoint)
}

return http.HandlerFunc(fn)
}

无耻插件:我在这里写了博客:http://elithrar.github.io/article/vue-react-ember-server-golang/

关于go - 当没有路由与 Gorilla 匹配时提供文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39196782/

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