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 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)