【问题标题】:Get base path in http.HandleFunc在 http.HandleFunc 中获取基本路径
【发布时间】:2022-11-11 08:58:00
【问题描述】:

是否可以从http.Requesthttp.ResponseWriter 中的http.HandleFunc 获取基本路径作为变量(http.HandleFunc 中的第一个参数)?

http.HandleFunc("/the-base-path/", func(w http.ResponseWriter, r *http.Request){
    // get "/the-base-path/" here as a variable
    ...
})

【问题讨论】:

  • http.Request 有一个 URL 类型的 *url.URL 字段,它有 Path 字段。那不适合你的需要吗?
  • @jub0bs 我需要第一个参数中定义的确切变量
  • 默认情况下,这是不可能的。为什么不简单地将有问题的模式分配给范围内的变量,第二个参数为http.HandleFunc

标签: go


【解决方案1】:

简短的回答:没有。

更长的答案。

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

为请求查找处理程序的函数mux.Handler 返回处理程序和相应的模式(又名"/the-base-path/"

但是你可以看到mux.ServeHTTPmux.Handler 返回的模式。处理程序没有直接的方法来识别与请求匹配的模式。

【讨论】:

    猜你喜欢
    • 2013-08-02
    • 2018-08-13
    • 2011-07-15
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    • 2017-05-16
    相关资源
    最近更新 更多