如何在Go中将参数传递给Alice中间件?

I am using justinas/alice middleware in Go, and I want to pass arguments to the function used in the middleware.

For example:

middlewareChain := alice.New(Func1(foo string,foo2 string))

How can I do that?

As mentioned by Motakjuq, you can't directly write a middleware that takes in options as an argument since they need to be of the signature func (http.Handler) http.Handler.

What you can do is make a function that generates your middleware function.

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
}

Then you can do the following

middlewareChain := alice.New(middlewareGenerator("foo","foo2"))

Maybe I didn't understand your question, if your params in Func1 change in every request, you can't pass the arguments to the function. If your function required some params when you register it with alice, you can return the required function, something like:

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)
    }
}

And if you want to use it

chain := alice.New(Func1("", "", "time out"))....