如何在 http 包处理 URL 之前重写 URL

Rob*_*uez 3 url http go

使用 node/express 可以做这样的事情

app.use(rewrite('/*', '/index.html'));
Run Code Online (Sandbox Code Playgroud)

go 中的等价物是什么?我试过使用 httputil.ReverseProxy,但这似乎完全不切实际。

fl0*_*cke 8

For a simple "catch all" you can just do

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "index.html")
})
Run Code Online (Sandbox Code Playgroud)

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)
})
Run Code Online (Sandbox Code Playgroud)