使用 node/express 可以做这样的事情
app.use(rewrite('/*', '/index.html'));
go 中的等价物是什么?我试过使用 httputil.ReverseProxy,但这似乎完全不切实际。
最佳答案
对于一个简单的“捕获所有”你可以这样做
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html")
})
“/”模式匹配所有内容。
对于更复杂的模式,您需要使用重写 url 的处理程序包装您的 mux。
// register your handlers on a new mux
mux := http.NewServeMux()
mux.HandleFunc("/path", func(w http.ResponseWriter, r *http.Request) {
// your handler code
})
...
rewrite := func(path string) string {
// your rewrite code, returns the new path
}
...
// rewrite URL.Path in here before calling mux.ServeHTTP
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
r.URL.Path = rewrite(r.URL.Path)
mux.ServeHTTP(w,r)
})
关于http - 如何在 URL 被 http 包处理之前重写它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35074703/