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

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

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

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:

确定