英文:
How can I rewrite the URL before it's being handled by the http package
问题
使用Node.js/Express,可以像这样实现:
app.use(rewrite('/*', '/index.html'));
在Go语言中,相应的实现方式是什么?我尝试使用httputil.ReverseProxy
,但似乎完全不实用。
英文:
With node/express its possible to do something like this
app.use(rewrite('/*', '/index.html'));
What would the equivalent in go be? I've tried using the httputil.ReverseProxy, but that seems entirely impractical.
答案1
得分: 8
对于一个简单的“捕获所有”操作,你可以这样做:
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html")
})
"/"模式匹配所有路径。
对于更复杂的模式,你需要使用一个处理程序来重写URL。
// 在一个新的mux上注册你的处理程序
mux := http.NewServeMux()
mux.HandleFunc("/path", func(w http.ResponseWriter, r *http.Request) {
// 处理程序的代码
})
...
rewrite := func(path string) string {
// 重写代码,返回新的路径
}
...
// 在调用mux.ServeHTTP之前在这里重写URL.Path
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
r.URL.Path = rewrite(r.URL.Path)
mux.ServeHTTP(w,r)
})
以上是你要翻译的内容。
英文:
For a simple "catch all" you can just do
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html")
})
The "/" pattern matches everything.
For a more complex pattern, you need to wrap your mux with a handler that rewrites the url.
// 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)
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论