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

huangapple go评论83阅读模式
英文:

How can I pass parameters to a alice middleware in Go?

问题

我正在使用Go语言中的justinas/alice中间件,并且我想将参数传递给中间件中使用的函数。

例如:

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

我该如何做到这一点?

英文:

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?

答案1

得分: 4

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) {
            // 使用 foo1 和 foo2
            h.ServeHTTP(w, r)
        })
    }
    return
}

然后你可以这样做:

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

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

答案2

得分: 1

也许我没有理解你的问题,如果你在每个请求中的Func1中的参数都会改变,那么你不能将参数传递给函数。如果你的函数在注册时需要一些参数,你可以返回所需的函数,类似于:

func Func1(foo, foo2, timeoutMessage string) alice.Constructor {
    //... 使用 foo 和 foo2 做一些操作
    return func(h http.Handler) http.Handler {
        return http.TimeoutHandler(h, 1*time.Second, timeoutMessage)
    }
}

如果你想使用它:

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

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"))....

huangapple
  • 本文由 发表于 2016年12月5日 16:51:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/40970343.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定