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 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂