dongqiuqiu4736 2016-10-11 10:05
浏览 30
已采纳

如何在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?

  • 写回答

1条回答 默认 最新

  • doutuan6158 2016-10-12 04:22
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?