duanreng3439 2017-10-02 04:39
浏览 100
已采纳

大猩猩Mux子路由方法POST请求触发GET

I'm trying to develop a simple REST API in Go, using Gorilla Mux.

I have the main.go which register the simple path above and start the server to listen on port 3000.

func main() {
    router := mux.NewRouter().StrictSlash(true)
    sub := router.PathPrefix("/api/v1").Subrouter()
    handlers.RegisterRoutes(sub)

    log.Fatal(http.ListenAndServe(":3000", router))
}

A basic handlers registration method inside another generic handlers.go file

func RegisterRoutes(sub *mux.Router) {
    user.RegisterRoutes(sub)
}

And the user.handler.go file, which register the "/user" subroute:

func RegisterRoutes(sub *mux.Router) {
    userRoutes := sub.StrictSlash(true).Path("/users").Subrouter()

    userRoutes.Methods("POST").HandlerFunc(getUsers)
    userRoutes.Methods("GET").HandlerFunc(getUsers)
}

func getUsers(w http.ResponseWriter, r *http.Request) {
    user := User{Name: "test", Password: "test"}

    fmt.Printf("%+v
", r.Method)

    json.NewEncoder(w).Encode(user)
}

I was testing the path that I've had set up above, and came up with an wird behavior:

Test - GET - localhost:3000/api/v1/users  => Prints GET in console. (as expected)
Test - GET - localhost:3000/api/v1/users/  => Prints GET in console. (as expected)
Test - POST - localhost:3000/api/v1/users  => Prints POST in console. (as expected)
Test - POST - localhost:3000/api/v1/users/  => Prints GET in console. (And here is the strange behavior)

When I send a POST to the endpoint(localhost:3000/api/users/) with the trailing slash at the end of the url it triggers the GET instead of the POST.

Anyone came across with this behavior using Gorilla Mux?

  • 写回答

1条回答 默认 最新

  • dragon_9000 2017-10-02 04:50
    关注

    The specific issue would be mux issue 79, which is still pending (even if closed), also seen in mux issue 254

    That seems also related to mux issue 145: StrictSlash is confusing

    This

    "When true, if the route path is "/path/", accessing "/path" will redirect to the former and vice versa. In other words, your application will always see the path as specified in the route."

    and

    "When false, if the route path is "/path", accessing "/path/" will not match this route and vice versa."

    should be inverted, because strict==true should mean no trailing slash allowed.
    It's name and docs are confusing.

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

报告相同问题?

悬赏问题

  • ¥15 有没有会使用flac3d软件的家人
  • ¥20 360摄像头无法解绑使用,请教解绑当前账号绑定问题,
  • ¥15 docker实践项目
  • ¥15 数电几道习题,写出作答过程,ai一律不采用
  • ¥15 利用pthon计算薄膜结构的光导纳
  • ¥15 海康hlss视频流怎么播放
  • ¥15 Paddleocr:out of memory error on GPU
  • ¥30 51单片机C语言数码管驱动单片机为AT89C52
  • ¥100 只改动本课件的 cal_portfolio_weight_series(decision_date), 跑完本课件。设计一个信息比率尽量高的策略。
  • ¥20 如何在visual studio 2022中添加ImageMagick库