dse323222 2015-04-07 01:53
浏览 27
已采纳

Negroni /大猩猩MUX的子路由器问题

So I am trying to setup my router to respond to /users and /users/{userId} so I tried this code:

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

The issue is that I get a 404 error when I go to /users (but is does respond to /users/) If I do:

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

It works like I want it to.

Is there any way to get the URLs to work like I want with Subrouters?

  • 写回答

1条回答 默认 最新

  • doushizhou4477 2015-04-07 19:58
    关注

    Yes and no. You can make the routes semi-work by adding StrictSlash(true) to the router.

    Given the following code

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

    a request to http://localhost:8080/users will return

    < 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>.
    

    a request to http://localhost:8080/users/ returns

    < 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
    

    so if your client is a browser then perhaps this is acceptable.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大