英文:
Get base path in http.HandleFunc
问题
http.HandleFunc函数的第一个参数是处理请求的路径,而不是基本路径。因此,无法直接从http.HandleFunc中获取基本路径。但是,你可以通过其他方式获取基本路径。
一种方法是使用http.Request的URL字段来获取请求的路径,并从中提取基本路径。你可以使用r.URL.Path来获取请求的路径,然后使用字符串操作函数来提取基本路径。
另一种方法是在http.HandleFunc之前定义一个变量来存储基本路径,并在处理函数中使用该变量。例如:
baseURL := "/the-base-path/"
http.HandleFunc(baseURL, func(w http.ResponseWriter, r *http.Request){
// 使用baseURL变量作为基本路径
...
})
这样,你就可以在处理函数中使用baseURL变量作为基本路径。
英文:
Is it possible to get the base path from the http.HandleFunc in the http.Request or http.ResponseWriter as a variable (first argument in http.HandleFunc) ?
http.HandleFunc("/the-base-path/", func(w http.ResponseWriter, r *http.Request){
// get "/the-base-path/" here as a variable
...
})
答案1
得分: 1
简短回答:不会。
较长回答:
处理请求的函数是 ServeHTTP,它的代码如下:
func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) {
if r.RequestURI == "*" {
if r.ProtoAtLeast(1, 1) {
w.Header().Set("Connection", "close")
}
w.WriteHeader(StatusBadRequest)
return
}
h, _ := mux.Handler(r)
h.ServeHTTP(w, r)
}
查找请求处理程序的函数是 mux.Handler,它返回处理程序和相应的模式(即 "/the-base-path/")。
但是,正如你可以看到的,mux.ServeHTTP 丢弃了 mux.Handler 返回的模式。处理程序无法直接识别与请求匹配的模式。
英文:
Short answer: no.
Longer answer.
The function that serves requests is
func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) {
if r.RequestURI == "*" {
if r.ProtoAtLeast(1, 1) {
w.Header().Set("Connection", "close")
}
w.WriteHeader(StatusBadRequest)
return
}
h, _ := mux.Handler(r)
h.ServeHTTP(w, r)
}
The function mux.Handler that looks up the handler for the request returns both the handler and the corresponding patter (aka "/the-base-path/")
But as you can see mux.ServeHTTP drops the pattern returned by mux.Handler. There is no direct way for the handler to identify the pattern that was matched against the request.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论