duandai3964 2019-09-17 13:29
浏览 7

如何实现子路由

I want to achieve routes like

user/profile

user/cart

user/products

Currently, I'm doing this

r.HandleFunc("user/signup", signupHandler).Methods("POST")
r.HandleFunc("user/signin", signinHandler).Methods("POST")
r.HandleFunc("user/profile", profileHandler).Methods("GET")
r.HandleFunc("user/cart", cartHandler).Methods("POST")
r.HandleFunc("user/products", productsHandler).Methods("GET")

As you can see these routes starts with user so can how can I know it's a user routes so I can send handle it in a different file.

I want something like

r.HandleFunc("user/", handlerWhichHandelAllTheRequestFromUser)

It should handle all the URL which starts from users.

I'm using mux gorilla

  • 写回答

1条回答 默认 最新

  • doulao1934 2019-09-17 13:41
    关注

    There is a PathPrefix function in mux. You can use it to make the path prefix i.e. "/user" in this case.

    example:-

    userHandler.go

    func makeUserHandler()http.Handler{
      //Define all you handlers here
      r := mux.NewRouter()
      r.HandleFunc("user/signup", signupHandler).Methods("POST")
      r.HandleFunc("user/signin", signinHandler).Methods("POST")
      r.HandleFunc("user/profile", profileHandler).Methods("GET")
      r.HandleFunc("user/cart", cartHandler).Methods("POST")
      r.HandleFunc("user/products", productsHandler).Methods("GET")
      return r
    }
    

    main.go

    r := mux.NewRouter()
    r.PathPrefix("/user").Handler(makeUserHandler())
    

    Please make necessary changes to the above code as per your requirement.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度