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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?