我在Go中使用justinas/alice中間件,我想將參數傳遞給中間件中使用的函數。如何將參數傳遞給Go中的alice中間件?
例如:
middlewareChain := alice.New(Func1(foo string,foo2 string))
我怎麼能這樣做?
我在Go中使用justinas/alice中間件,我想將參數傳遞給中間件中使用的函數。如何將參數傳遞給Go中的alice中間件?
例如:
middlewareChain := alice.New(Func1(foo string,foo2 string))
我怎麼能這樣做?
正如Motakjuq
提到的,你不能直接寫一箇中間件,在選擇帶一個參數,因爲他們需要簽名func (http.Handler) http.Handler
的。
你可以做的是做一個函數來生成你的中間件功能。
func middlewareGenerator(foo, foo2 string) (mw func(http.Handler) http.Handler) {
mw = func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Use foo1 & foo2
h.ServeHTTP(w, r)
})
}
return
}
然後,你可以做以下
middlewareChain := alice.New(middlewareGenerator("foo","foo2"))
也許我不明白你的問題,如果你在每次請求Func1
變化參數,可以,你不能傳遞參數給功能。如果您需要的功能部分,當你與愛麗絲註冊它PARAMS,你可以返回所需的功能,這樣的:
func Func1(foo, foo2, timeoutMessage string) alice.Constructor {
//... something to do with foo and foo2
return func(h http.Handler) http.Handler {
return http.TimeoutHandler(h, 1*time.Second, timeoutMessage)
}
}
如果你想使用它
chain := alice.New(Func1("", "", "time out"))....
你不能,DOC中間件func應該具有'func(http.Handler)http.Handler'的形式,你必須找出不同的方法,如會話數據或其他存儲機制。 – Motakjuq
還想補充一點,使用Context是另一種選擇,這就是它的用處。 – saarrrr