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

时间:2016-01-29 00:16:16

标签: http url go

使用node / express可以执行类似这样的操作

app.use(rewrite('/*', '/index.html'));

相同的东西是什么?我尝试过使用httputil.ReverseProxy,但这似乎完全不切实际。

1 个答案:

答案 0 :(得分:4)

对于一个简单的"赶上所有"你可以做到

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)
})