如何在GO中为不同路径使用不同的中间件?

Hi I am using justinas/alice, and I want to create different middlewares based on paths. i.e if I have path1 and path2, I want to apply m1,m2,m3 for path 1 and m1,m2 for path 2

I tried:

  • Creating two mux routers first:

router := mux.NewRouter() router2 := mux.NewRouter()

  • Assign the paths to them:

router.HandleFunc(path1,Func1) router2.HandleFunc(path2,Func2)

  • Then I wanted to have something like this

middlewares:=alice.New(m1,m2).Then(router2) middlewaress:=middlewares.Append(middlewares) - Then:

if err := http.ListenAndServe(fmt.Sprintf(":%d", sconf.Server.Port), middlewaress); err != nil {

    }

how can I do something like this?

You need to let set the handlers for router and router to the returned chain from alice.

// define routers
router := mux.NewRouter() // assuming this is gorilla mux
router2 := mux.NewRouter()

// create alice chains
chain1 := alice.New(m1, m2, m3).Then(func1)
chain2 := alice.New(m1, m2).Then(func2)

// set chains as path handlers
router.HandleFunc(path1, chain1)
router2.HandleFunc(path2, chain2)