doulue1949 2016-12-05 08:51
浏览 198
已采纳

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

  • 写回答

2条回答 默认 最新

  • dongqian3198 2016-12-05 11:07
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决
  • ¥15 gsoap生成onvif框架