gpt4 book ai didi

go - negroni/gorilla mux 的子路由器问题

转载 作者:数据小太阳 更新时间:2023-10-29 03:16:57 26 4
gpt4 key购买 nike

所以我正在尝试设置我的路由器以响应 /users/users/{userId} 所以我尝试了这段代码:

usersRouter := router.PathPrefix("/users").Subrouter()
usersRouter.HandleFunc("", users.GetUsersRoute).Methods("GET")
usersRouter.HandleFunc("/{userId:[0-9]*}", users.GetUserRoute).Methods("GET")

问题是当我转到 /users 时出现 404 错误(但确实响应 /users/)如果我这样做:

router.HandleFunc("/users", users.GetUsersRoute).Methods("GET")
router.HandleFunc("/users/{userId:[0-9]*}", users.GetUserRoute).Methods("GET")

它像我想要的那样工作。

有什么方法可以让 URL 像我希望的那样使用 Subrouter 工作吗?

最佳答案

是也不是。您可以通过向路由器添加 StrictSlash(true) 使路由半工作。

给定以下代码

package main

import (
"fmt"
"net/http"

"github.com/gorilla/mux"
)

func main() {
mainRouter := mux.NewRouter().StrictSlash(true)
mainRouter.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "test") })

subRouter := mainRouter.PathPrefix("/users").Subrouter()
subRouter.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "/users") })
subRouter.HandleFunc("/{id:[0-9]+}", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "/users/id") })
http.ListenAndServe(":8080", mainRouter)
}

请求http://localhost:8080/users会回来的

< HTTP/1.1 301 Moved Permanently
< Location: /users/
< Date: Tue, 07 Apr 2015 19:52:12 GMT
< Content-Length: 42
< Content-Type: text/html; charset=utf-8
<
<a href="/users/">Moved Permanently</a>.

请求http://localhost:8080/users/返回

< HTTP/1.1 200 OK
< Date: Tue, 07 Apr 2015 19:54:43 GMT
< Content-Length: 6
< Content-Type: text/plain; charset=utf-8

< /users

因此,如果您的客户端是浏览器,那么这也许是可以接受的。

关于go - negroni/gorilla mux 的子路由器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29482453/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com