doutang1946 2015-08-26 19:04
浏览 32
已采纳

将参数传递给Negroni中间件

Every request to my application should use some middleware. Using the Negroni docs I have implemented it like so:

func MyMiddleware(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
  // do some stuff before
  next(rw, r)
}

and elsewhere I use:

n.Use(negroni.HandlerFunc(MyMiddleware))

However, the middleware needs to receive an extra argument and I'm not sure how to build this in. At the moment I'm just setting the value as a global variable to make it available but I'm sure there's a more elegant way?

I would like to be able to do something like this:

n.Use(negroni.HandlerFunc(MyMiddleware(val)))
  • 写回答

1条回答 默认 最新

  • doudun1934 2015-08-26 20:04
    关注

    The best way would be to encapsulate your middleware as a struct that holds its state, not just a stateless function. (You could also wrap it as a closure but a struct is cleaner IMO):

    type MyMiddleware struct {
        someval string
    }
    
    func NewMyMiddleware(someval string) *MyMiddleware {
        return &MyMiddleware{
           someval: someval,
        }
    }
    
    
    func (m *MyMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
    
        // Do Something with someval
        fmt.Println(m.someval)
    
        next(w, req)
    }
    

    and initializing it is simply:

    n.Use(NewMyMiddleware("foo"))
    

    EDIT: Perhaps a closure would actually be simple:

     someval := foo
    
     n.Use(negroni.HandlerFunc(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
       // Do Something with someval
       fmt.Println(someval)
    
       next(w, req)
    }))
    

    Or you could have a function that returns a middleware function:

    func NewMiddleware(someval string) negroni.HandlerFunc {
         return negroni.HandlerFunc(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
           // Do Something with someval
           fmt.Println(someval)
    
           next(w, req)
        })
    }
    

    and then

    n.Use(NewMiddleware("foo"))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题