英文:
Is it possible to know what route is used in HandleFunc
问题
我正在使用net/http
包中的http.HandleFunc("/resource", resource.Handle)
,我想知道是否有一种方法可以查看到达resource.Handle
的路由(在这种情况下是/resource
)?还是说我必须创建一个Mux
来实现这个功能?
我想知道这个是为了从URL路径中提取资源,以便进行一些操作...
英文:
I am using http.HandleFunc("/resource", resource.Handle)
from the package net/http
and I was wondering if there was a way to see what route (in this case /resource
) is used to get you to resource.Handle
? Or do I have to create a Mux
for this?
I'd like to know this to extract the resource from the url path to do some magic with it...
答案1
得分: 3
使用request.URL.Path
来获取访问处理程序的路径。
英文:
http://golang.org/pkg/net/http/#Request
Use request.URL.Path
to get the path used to access the handler.
答案2
得分: 3
是的,你可以这样做:
- 使用
HandleFunc
方法使用的DefaultServeMux
。 - 构造一个假的
http.Request
。
例如:
package main
import (
"fmt"
"net/http"
"net/url"
)
func main() {
theUrl, err := url.Parse("/response")
if err != nil {
fmt.Println(err.Error())
return
}
http.HandleFunc("/response", func(w http.ResponseWriter, r *http.Request) {
})
handler, path := http.DefaultServeMux.Handler(&http.Request{Method: "GET", URL: theUrl})
fmt.Println(handler, path)
}
可以在Go Playground上查看示例。
英文:
Yes you can
The main points to do:
- Use the
DefaultServeMux
used by theHandleFunc
method. - Construct a fake
http.Request
For Example:
package main
import (
"fmt"
"net/http"
"net/url"
)
func main() {
theUrl, err := url.Parse("/response")
if err != nil {
fmt.Println(err.Error())
return
}
http.HandleFunc("/response", func(w http.ResponseWriter, r *http.Request) {
})
handler, path := http.DefaultServeMux.Handler(&http.Request{Method: "GET", URL: theUrl})
fmt.Println(handler, path)
}
see this Go Playground
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论