Gorilla mux routing with multiple sub packages - Cycle import issue

435 views
Skip to first unread message

Mahesh Haldar

unread,
Dec 11, 2015, 4:45:20 AM12/11/15
to golang-nuts
Here is my project structure
--main package
--|--child_package1
--|--child_package2
--|--child_packege3

I have all the the routes and method call for API hit listed in main_package

router Handle from main_package.go

func Handlers(db *sql.DB, customeruploadFile string) *mux.Router {
router := mux.NewRouter()
router.HandleFunc("/api1", child_package1.method )
router.HandleFunc("/api2", child_package2.method)
        router.HandleFunc("/api3", child_package3 .mehtod)

fileHandler := http.FileServer(http.Dir("./client/compiled"))
router.PathPrefix("/").Handler(http.StripPrefix("/", fileHandler))
return router
}

now the problem is when I write test cases for child packegs, I need this Handlers method to create test server, for that I need to import main_package in child_packages, then as obvious there is cycle imports happening, as child_packages are imported in main_pakcage.
Can any one please suggest me the best approach to tackle this.
Thanks

Frits van Bommel

unread,
Dec 11, 2015, 7:00:43 AM12/11/15
to golang-nuts
In a similar situation I just moved the mux to its own "router" package. That should work for you too.

Mahesh Haldar

unread,
Dec 11, 2015, 7:37:57 AM12/11/15
to golang-nuts
Can you please elaborate more? Pseudo code will also work.
Thanks

Frits van Bommel

unread,
Dec 11, 2015, 9:08:16 AM12/11/15
to golang-nuts
Oh, I didn't see you meant the function that configures the router instead of the router itself. I basically have a global Router variable that gets configured from a init() functions. (App Engine pretty much requires this)

You could do it like me and create a global Mux instance you can put in a different package (configuring it, in my case, from init function(s) in the packages themselves). Then you can use the same router variable from your tests.

Alternatively, you could name your test package differently and import your regular packages. (test files are special in that their package name doesn't have to match the package name of other files in the directory)
That would look something like this:

    // file mypackage/child1/foo_test.go
   
    package child1_test
   
    import (
        "mypackage/child1"
        "testing"
        // ...
    )
   
    func TestFoo(t *testing.T) { /* ... */ }
Reply all
Reply to author
Forward
0 new messages