1

I have the following routes:

router.Methods("POST").Path("/my_post_01").HandlerFunc(myHandler1)
router.Methods("GET").Path("/my_get_01").HandlerFunc(myHandler2)

router.Methods("POST").Path("/my_post_02").HandlerFunc(myHandler3)
router.Methods("GET").Path("/my_get_02").HandlerFunc(myHandler4)

router.Methods("POST").Path("/my_post_03").HandlerFunc(myHandler5)
router.Methods("GET").Path("/my_get_03").HandlerFunc(myHandler6)

router.Methods("POST").Path("/my_post_04").HandlerFunc(myHandler7)
router.Methods("GET").Path("/my_get_04").HandlerFunc(myHandler8)

router.Methods("POST").Path("/my_post_05").HandlerFunc(myHandler9)
router.Methods("GET").Path("/my_get_05").HandlerFunc(myHandler10)

As I have more and more routes, it gets harder to manage.

I want to do something like:

router.Path("/my/*").HandleFunc(mypackage.RegisterHandler)

with all handlers being separated in another package

Is there any way that I can match those paths in a separate package?

Thanks,

  • ...have you tried what you put here? There is nothing stopping you from passing a `http.HandlerFunc` that resides in another package to your router... – Simon Whitehead Feb 05 '15 at 21:12

2 Answers2

2

You could create a package for your router then import said package and add your routes.

Router

package router

var Router = mux.NewRouter()
// handle "/my/" routes
var MyRouter = Router.PathPrefix("/my").Subrouter()

another package

import "/path/to/router"

func init() {
    router.MyRouter.Methods("POST").Path("/post_01").HandlerFunc(myHandler1)
}

In main

import "/path/to/router"

func main() {
    http.Handle("/", router.Router)

    //...
}
jmaloney
  • 11,580
  • 2
  • 36
  • 29
  • Then how do I avoide prefixing `my_` to every handler? –  Feb 06 '15 at 21:17
  • @cvxv31431asdas I added a subrouter example. It does not let you add `my_` but it does allow for a path prefix of `/my/`. – jmaloney Feb 06 '15 at 22:01
2

It would be a lot better if you could extract id from the request URL and handle it in a generic handler.

Actually, it is not far from where you are right now, modify you router like this:

r := mux.NewRouter()
r.Methods("POST").HandleFunc("/articles/{article_id:[0-9]+}", ArticlePostHandler)

article_id is the parameter name and [0-9]+ is the regexp to match it.

And in the ArticlePostHandler (you could import it from another package), use mux.Vars to get the id, like this:

func ArticlePostHandler(resp http.ResponseWriter, req *http.Request) {
   articleId := mux.Vars(req)["article_id"]
   // do whatever you want with `articleId`
}

Document: http://www.gorillatoolkit.org/pkg/mux

Andy Xu
  • 1,107
  • 8
  • 10