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

标签 http url go

使用 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/

相关文章:

node.js - 为什么后续的 HTTP 请求

javascript - 在 Chrome 中使用 window.location.reload 从缓存加载和哈希片段不起作用

Javascript:判断 URL 是否等于一个字符串,有或没有尾部斜线

python - 在 url 调度中存储 bool 变量

go - 如何使用 Go 的 ssh 包创建 socks5 隧道?

go - 如何模拟 amqp.Dial 等库中的函数

PHP:从 MS Office 中的链接加入浏览器 session

c++ - 从主机向在 VirtualBox Linux 机器上运行的服务器发送 http 请求

xml - 如何在 golang 中编码 CDATA 与使用换行符输入数据相同

带有获取查询的 Python 分页