Golang中为什么/post/{id}接口无法接收到请求

Golang中为什么/post/{id}接口无法接收到请求 我有一个小型HTTP服务器

  http.HandleFunc("/", router.Root)
http.HandleFunc("/post", router.Post)
http.HandleFunc("/post/{id}", router.PostRet)
http.ListenAndServe(":8080", nil)

为什么当我向localhost:8080/post/2发送请求时,响应来自"/“根处理程序?当我写”/post/{id}"时,请求URL应该是类似"localhost:8080/post/?id=222"这样的格式吗?


更多关于Golang中为什么/post/{id}接口无法接收到请求的实战教程也可以访问 https://www.itying.com/category-94-b0.html

6 回复

我正在使用 net/http

更多关于Golang中为什么/post/{id}接口无法接收到请求的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


你使用的是哪个服务器/多路复用器?我在默认文档中找不到这种语法。

那么你建议使用像 gorilla mux 这样的外部库吗?

要么使用常规查询参数,要么自行实现能够处理这种情况的多路复用器。

而且它不支持这种语法,你实际上是在为 /post/{id} 添加一个处理器。在你的浏览器中尝试完全相同的 URL…

// 代码示例
func main() {
    fmt.Println("hello world")
}

在Go的标准库net/http中,路由模式不支持像/post/{id}这样的参数化路径。当使用http.HandleFunc时,模式匹配是基于前缀的,但需要明确指定路径格式。

在你的代码中,/post/{id}不会被识别为带参数的路径,而是被当作字面字符串处理。当请求/post/2时,由于没有精确匹配的处理程序,它会回退到根路径/的处理程序。

要处理类似/post/2的路径,你有几个选择:

  1. 使用固定路径模式:
http.HandleFunc("/post/", router.PostRet) // 注意结尾的斜杠

然后在处理函数中解析ID:

func PostRet(w http.ResponseWriter, r *http.Request) {
    // 从路径中提取ID
    path := r.URL.Path
    id := path[len("/post/"):]
    
    // 使用ID进行处理
    fmt.Fprintf(w, "Post ID: %s", id)
}
  1. 使用第三方路由库,如gorilla/mux:
r := mux.NewRouter()
r.HandleFunc("/post/{id}", router.PostRet)
http.ListenAndServe(":8080", r)

在gorilla/mux中,处理函数可以这样获取参数:

func PostRet(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    id := vars["id"]
    fmt.Fprintf(w, "Post ID: %s", id)
}

关于URL格式的问题:/post/2是RESTful风格的路径参数,而/post?id=222是查询参数。两者都是有效的,但实现方式不同。你的原始意图似乎是想要路径参数。

修正后的代码示例:

http.HandleFunc("/", router.Root)
http.HandleFunc("/post", router.Post) // 处理 /post
http.HandleFunc("/post/", router.PostRet) // 处理 /post/ 开头的所有路径

func PostRet(w http.ResponseWriter, r *http.Request) {
    path := strings.TrimPrefix(r.URL.Path, "/post/")
    if path == "" {
        http.NotFound(w, r)
        return
    }
    fmt.Fprintf(w, "Post ID: %s", path)
}

这样配置后,请求localhost:8080/post/2就会由PostRet处理程序正确响应。

回到顶部