在http包处理URL之前,我该如何重写URL?

huangapple go评论120阅读模式
英文:

How can I rewrite the URL before it's being handled by the http package

问题

使用Node.js/Express,可以像这样实现:

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

在Go语言中,相应的实现方式是什么?我尝试使用httputil.ReverseProxy,但似乎完全不实用。

英文:

With node/express its possible to do something like this

  1. 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

对于一个简单的“捕获所有”操作,你可以这样做:

  1. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  2. http.ServeFile(w, r, "index.html")
  3. })

"/"模式匹配所有路径。

对于更复杂的模式,你需要使用一个处理程序来重写URL。

  1. // 在一个新的mux上注册你的处理程序
  2. mux := http.NewServeMux()
  3. mux.HandleFunc("/path", func(w http.ResponseWriter, r *http.Request) {
  4. // 处理程序的代码
  5. })
  6. ...
  7. rewrite := func(path string) string {
  8. // 重写代码,返回新的路径
  9. }
  10. ...
  11. // 在调用mux.ServeHTTP之前在这里重写URL.Path
  12. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  13. r.URL.Path = rewrite(r.URL.Path)
  14. mux.ServeHTTP(w,r)
  15. })

以上是你要翻译的内容。

英文:

For a simple "catch all" you can just do

  1. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  2. http.ServeFile(w, r, "index.html")
  3. })

The "/" pattern matches everything.

For a more complex pattern, you need to wrap your mux with a handler that rewrites the url.

  1. // register your handlers on a new mux
  2. mux := http.NewServeMux()
  3. mux.HandleFunc("/path", func(w http.ResponseWriter, r *http.Request) {
  4. // your handler code
  5. })
  6. ...
  7. rewrite := func(path string) string {
  8. // your rewrite code, returns the new path
  9. }
  10. ...
  11. // rewrite URL.Path in here before calling mux.ServeHTTP
  12. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
  13. r.URL.Path = rewrite(r.URL.Path)
  14. mux.ServeHTTP(w,r)
  15. })

huangapple
  • 本文由 发表于 2016年1月29日 08:16:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/35074703.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定