如何将参数传递给 Go 中的 alice 中间件?
How can I pass parameters to a alice middleware in Go?
我在 Go 中使用 justinas/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
中的参数在每个请求中都发生变化,你就不能将参数传递给函数。如果您的函数在向 alice 注册时需要一些参数,您可以 return 所需的函数,例如:
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"))....
我在 Go 中使用 justinas/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
中的参数在每个请求中都发生变化,你就不能将参数传递给函数。如果您的函数在向 alice 注册时需要一些参数,您可以 return 所需的函数,例如:
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"))....