Reputation:
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,
Upvotes: 1
Views: 6188
Reputation: 12320
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)
//...
}
Upvotes: 2
Reputation: 1147
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
Upvotes: 2